基本介绍:
1)高层模块不应该依赖低层模块,二者应该依赖其抽象
2)抽象不应该依赖细节,细节应该依赖抽象
3)依赖倒转的思想:面向接口编程
4)相对于细节的多变性,抽象的东西要稳定得多。抽象指的是接口或抽闲类,细节就是具体的实现类
5)使用接口或抽象类的目的是制定规范,不涉及任何操作,把展示细节的任务交给实现类去完成。
实现方案1:
class Email{
public String getInfo(){
return "电子邮件信息:hello world";
}
}
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());
}
}
改进:增加IReceive接口
public interface IReceive {
public String getInfo();
}
class Email implements IReceive{
public String getInfo(){
return "电子邮件信息:hello world";
}
}
class WeChat implements IReceive{
@Override
public String getInfo() {
return "微信消息:hello ok";
}
}
class Person{
public void receive(IReceive iReceive){
System.out.println(iReceive.getInfo());
}
}
public class DependencyInversion {
public static void main(String[] args) {
Person person = new Person();
person.receive(new Email());
person.receive(new WeChat());
}
}
实现二:
接口IOpenAndClose
public interface IOpenAndClose {
public void open(ITV tv);
}
接口:ITV
public interface ITV {
public void play();
}
class ChangHong implements ITV{
@Override
public void play() {
System.out.println("长虹电视机,打开");
}
}
class OpenAndClose implements IOpenAndClose{
@Override
public void open(ITV tv) {
tv.play();
}
}
public class DependencyPass {
public static void main(String[] args) {
ChangHong changHong = new ChangHong();
OpenAndClose openAndClose = new OpenAndClose();
openAndClose.open(changHong);
}
}