设计模式:4.设计模式的七大原则之三(依赖倒转原则)

208 阅读2分钟

依赖倒转原则(Dependence Inversion Principle)

1.基本介绍
  • 高层模块不应该依赖底层模块,二者都应该依赖其抽象(抽象类、接口)
  • 抽象不应该依赖细节,细节应该依赖抽象
  • 依赖倒转(倒置)的中心思想是面向接口编程
  • 依赖倒转原则的设计理念:相对于细节(具体的实现类)的多变性,抽象(接口或抽象类)的东西要稳定的多。以抽象为基础搭建的架构比以细节为基础的架构要稳定的多。
  • 使用接口或抽象类的目的是制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类去完成。
2.不使用依赖倒转原则实现:手机接收消息

(1) 新建Email类,作为消息的一种

public class Email{
	// 获取Email内容
    public String getEmailContent(){
    	return "消息(Email)的内容";
    }
}

(2) 新建手机类,接收消息

public class Mobile{
	// 手机接收到Email
    public String receiveInfo(Email email){
    	System.out.println(email.getEmailContent());
    }
}

(3) 模拟手机接收消息

public class doMobile{
    public static void main(String[] args) {
    	Mobile mobile = new Mobile();
		mobile.receiveInfo(new Email());	// 手机接收到Email
    }
}

以上,如果我们现在需要新增一个消息类型,例如微信,则需要新加微信消息类、新增手机接收微信消息方法等,比较麻烦。

3.使用依赖倒转原则实现:手机接收多种消息

(1) 新建消息接口

public interface Info {
	// 获取消息内容
	String getInfoContent();
}

(2) 新建Email类,作为消息的一种

public class Email implements Info{
	// 实现获取消息内容
	@Override
    public void getInfoContent() {
        System.out.println("消息(Email)的内容");
    }
}

(3) 新建手机类,接收消息

public class Mobile{
	// 手机接收到消息
    public String receiveInfo(Info info){
    	System.out.println(info.getInfoContent());
    }
}

(4) 模拟手机接收消息

public class doMobile{
    public static void main(String[] args) {
    	Mobile mobile = new Mobile();
		mobile.receiveInfo(new Email());	// 手机接收到Email
    }
}

当我们需要新增一种消息类型,例如微信时:
(5) 新建Email类,作为消息的一种

public class Wechat implements Info{
	// 实现获取消息内容
	@Override
    public void getInfoContent() {
        System.out.println("消息(微信)的内容");
    }
}

(6) 模拟手机接收消息

public class doMobile{
    public static void main(String[] args) {
    	Mobile mobile = new Mobile();
		mobile.receiveInfo(new Email());	// 手机接收到Email

		mobile.receiveInfo(new Wechat());	// 手机接收到微信
    }
}

手机类都没有改动,因为手机类依赖的是抽象的接口,因此稳定性很好。

4.依赖关系的传递方式

以例子说明三种传递方式:

  • (1) 接口传递
  • (2) 构造方法传递
  • (3) setter方式传递