一、依赖倒转原则介绍
二、依赖倒转原则引入
1.方式一(传统方式)
public class DependencyInversion {
public static void main(String[] args) {
Person person = new Person();
person.receive(new Email());
}
}
class Email {
public String getInfo() {
return "电子邮件信息:hello,world";
}
}
//完成Person接收消息的功能
//方式1分析
//1.简单,比较容易想到
//2.如果我们获取的对象是微信,短信等等,则新增类,同时Person也要增加相应的接收方法
//3.解决思路:引入一个抽象的接口IReceiver,表示接收者,这样Person类与接口IReceiver发生依赖
//因为Email,WeiXin等等属于接收的范围,他们各自实现IReceiver接口就ok,这样我们就符合依赖倒转原则
class Person {
public void receive(Email email){
System.out.println(email.getInfo());
}
}
2.方式二(传统方式引入接口)
public class DependencyInversion {
public static void main(String[] args) {
//客户端无需改变
Person person = new Person();
person.receive(new Email());
person.receive(new WeiXin());
}
}
//定义一个接口
interface IReceiver {
String getInfo();
}
class Email implements IReceiver{
public String getInfo() {
return "电子邮件信息:hello,world";
}
}
class WeiXin implements IReceiver{
public String getInfo() {
return "微信消息:hello,ok";
}
}
class Person {
public void receive(IReceiver ireceiver){
System.out.println(ireceiver.getInfo());
}
}
3.方式三(接口传递、构造方法传递、setter方式传递)
public class DependencyPass {
public static void main(String[] args) {
//方式1: 通过接口传递实现依赖
// ChangHong changHong = new ChangHong();
// OpenAndClose openAndClose = new OpenAndClose();
// openAndClose.open(changHong);
// 方式2: 通过构造方法依赖传递
// ChangHong changHong = new ChangHong();
// OpenAndClose openAndClose = new OpenAndClose(changHong);
// openAndClose.open();
// 方式3 , 通过setter方法传递
ChangHong changHong = new ChangHong();
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.setTv(changHong);
openAndClose.open();
}
}
// 方式1: 通过接口传递实现依赖
// 开关的接口
// interface IOpenAndClose {
// public void open(ITV tv); //抽象方法,接收接口
// }
//
// interface ITV { //ITV接口
// public void play();
// }
//
// class ChangHong implements ITV {
//
// @Override
// public void play() {
// System.out.println("长虹电视机,打开");
// }
//
// }
// 实现接口
// class OpenAndClose implements IOpenAndClose{
// public void open(ITV tv){
// tv.play();
// }
// }
// 方式2: 通过构造方法依赖传递
// interface IOpenAndClose {
// public void open(); //抽象方法
// }
// interface ITV { //ITV接口
// public void play();
// }
//
//class ChangHong implements ITV {
//
// @Override
// public void play() {
// System.out.println("长虹电视机,打开");
// }
//
//}
// class OpenAndClose implements IOpenAndClose{
// public ITV tv;
// public OpenAndClose(ITV tv){
// this.tv = tv;
// }
// public void open(){
// this.tv.play();
// }
// }
// 方式3 , 通过setter方法传递
interface IOpenAndClose {
public void open(); // 抽象方法
public void setTv(ITV tv);
}
interface ITV { // ITV接口
public void play();
}
class ChangHong implements ITV {
@Override
public void play() {
System.out.println("长虹电视机,打开");
}
}
class OpenAndClose implements IOpenAndClose {
private ITV tv;
public void setTv(ITV tv) {
this.tv = tv;
}
public void open() {
this.tv.play();
}
}
三、依赖倒转原则注意事项和细节