基本介绍
- 高层模块不应该依赖底层模块,二者都应该依赖其抽象
- 抽象不应该依赖细节,细节应该依赖抽象
- 依赖倒转(倒置)的中心思想是面向接口编程
- 依赖倒转原则是基于这样的设计理念:相对于细节的多变性,抽象的东西要稳定的多。以抽象的基础搭建的架构比以细节为基础的架构要稳定的多,在Java中,抽象指的是接口和抽象类,细节就是具体的实现类
- 使用接口或抽象类的目的是制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类去完成
实例展示
不使用依赖倒置原则
class Email{
public String getInfo(){
return "this is a message";
}
}
// 完成 Person 接收消息的功能
// 方式1
/*
1. 简单,比较容易想到
2. 如果我们获取的对象时微信,短信等,则新增类,同时 Persons 也要增加相应的接收方法
3. 解决思路:引入一个抽象的接口 IReceiver,表示接收者,这样 Person 类 与接口 IReceiver 发生依赖
因为 Email,WeChat 等属于接收的范围,他们各自实现 IReceiver 接口就 ok,这样我们就符合依赖倒转原则
*/
class Person{
public void receive(Email email){
System.out.println(email.getInfo());
}
}
使用依赖倒置原则
// 定义接口
interface IReceiver{
public String getInfo();
}
// Email方式
class Email1 implements IReceiver{
public String getInfo() {
return "Info: this is a email";
}
}
// weChat方式
class WeChat implements IReceiver{
public String getInfo(){
return "info: this is a WeChat message";
}
}
class Person1{
public void receiver(IReceiver iReceiver){
System.out.println(iReceiver.getInfo());
}
}
// 测试
public static void main(String[] args) {
Person1 person1 = new Person1();
person1.receiver(new Email1());
person1.receiver(new WeChat());
}
// 结果输出:
Info: this is a email
info: this is a WeChat message
实现的三种方式
方式1:通过接口传递实现依赖
方式2:通过构造器方法传递依赖
方式3:通过setter方法传递
方式1
interface ITV{
public void play();
}
interface IOpenAndClose{
public void open(ITV tv);
}
class OpenAndClose implements IOpenAndClose{
public void open(ITV itv){
itv.play();
}
}
方式2:
terface IOpenAndClose{
public void open();
}
interface ITV{
public void play();
}
class OpenAndClose implements IOpenAndClose{
public ITV itv;
public OpenAndClose(ITV itv){
this.itv = itv;
}
public void open(){
this.itv.play();
}
}
方式3:
interface ITV{
public void play();
}
interface IOpenAndClose{
public void open();
public void setTv(ITV tv);
}
class OpenAndClose implements IOpenAndClose{
private ITV itv;
public void setTv(ITV itv){
this.itv = itv;
}
public void open(){
this.itv.play();
}
}
对以上三种方式将进行测试
首先定义一个 长虹 类
class CH implements ITV{
public void play(){
System.out.println("changHong TV is opening");
}
}
主方法中进行测试
方式1:
CH ch = new CH();
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.open(ch);
方式2:
CH ch1 = new CH();
OpenAndClose openAndClose = new OpenAndClose(ch1);
openAndClose.open();
方式3:
CH ch2 = new CH();
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.setTv(ch2);
openAndClose.open();