依赖倒置及其代码演示
时间: 2023-10-06 11:08:17 浏览: 48
依赖倒置原则(Dependency Inversion Principle,简称DIP)是面向对象设计原则的一种,它强调高层模块(稳定)不应该依赖于低层模块(变化),二者都应该依赖于抽象接口(稳定)。具体来说,依赖倒置原则要求通过抽象来解耦高层模块和低层模块之间的直接依赖关系,使得系统更加灵活、可扩展、易维护。
以下是一个简单的代码示例来演示依赖倒置原则:
```java
// 抽象接口
interface IMessage {
void sendMessage(String message);
}
// 低层模块实现接口
class EmailMessage implements IMessage {
@Override
public void sendMessage(String message) {
// 发送邮件
System.out.println("Sending email: " + message);
}
}
// 高层模块依赖抽象接口
class Notification {
private IMessage message;
public Notification(IMessage message) {
this.message = message;
}
public void sendNotification(String content) {
// 使用抽象接口发送通知
message.sendMessage(content);
}
}
// 测试代码
public class Main {
public static void main(String[] args) {
// 创建具体实现类对象
IMessage emailMessage = new EmailMessage();
// 通过构造函数注入依赖
Notification notification = new Notification(emailMessage);
// 发送通知
notification.sendNotification("Hello, World!");
}
}
```
在上述示例中,Notification 高层模块依赖于抽象接口 IMessage,而不依赖于具体的低层模块 EmailMessage。这样,如果以后需要替换 EmailMessage 实现,只需提供另一个实现了 IMessage 接口的类即可,不需要修改 Notification 高层模块的代码,实现了模块之间的解耦。
这就是依赖倒置原则的思想,通过面向接口编程,使得系统的各个模块之间更加松耦合,提高代码的可维护性和可扩展性。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)