标签:color receiver 依赖倒转原则 out turn close 设计 this loading
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()); } }
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()); } }
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(); } }
标签:color receiver 依赖倒转原则 out turn close 设计 this loading
原文地址:https://www.cnblogs.com/RobertYu666/p/14956343.html