依赖倒置原则

依赖倒置原则(Dependency Inversion Principle, DIP)是面向对象设计原则中的一条,它要求高层模块不应该依赖低层模块,二者都应该依赖其抽象。抽象不应该依赖细节,细节应该依赖抽象。简单来说,就是要针对接口编程,而不是针对实现编程。

下面是一个简单的 Java 示例代码:

//抽象接口
interface MessageSender {
    void send(String message);
}

//低层模块实现类
class EmailSender implements MessageSender {
    @Override
    public void send(String message) {
        System.out.println("通过Email发送消息:" + message);
    }
}

//另一个低层模块实现类
class SMSSender implements MessageSender {
    @Override
    public void send(String message) {
        System.out.println("通过短信发送消息:" + message);
    }
}

//高层模块类
class Notification {
    private MessageSender messageSender;

    public Notification(MessageSender messageSender) {
        this.messageSender = messageSender;
    }

    public void sendNotification(String message) {
        messageSender.send(message);
    }
}

//客户端代码
public class Client {
    public static void main(String[] args) {
        MessageSender emailSender = new EmailSender();
        Notification notificationByEmail = new Notification(emailSender);
        notificationByEmail.sendNotification("Hello World!");

        MessageSender smsSender = new SMSSender();
        Notification notificationBySms = new Notification(smsSender);
        notificationBySms.sendNotification("Hello World!");
    }
}

代码中,抽象接口 MessageSender 定义了发送消息的方法,而 EmailSenderSMSSender 是具体实现类。Notification 是高层模块类,它通过 MessageSender 接口依赖 EmailSenderSMSSender 实现类。客户端代码通过实例化 EmailSenderSMSSender 对象来创建通知方式,并调用 NotificationsendNotification 方法发送消息。

在这个示例中,高层模块 Notification 依赖的是抽象接口 MessageSender,而不是具体实现类 EmailSenderSMSSender。这样可以灵活地更换实现类或新增实现类,而不会影响到高层模块的代码。同时,通过依赖注入的方式,也可以实现对实现类的解耦。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值