依赖倒转原则简述
1.高层模块不应该依赖低层模块,二者都应该依赖其抽象
2.抽象不应该依赖细节,细节应该依赖抽象
3.依赖倒转得中心思想时面向接口编程
4.依赖倒转原则时基于这样得设计理念:相对于细节得多变性,抽象得东西要稳定得多。以抽象为基础搭建的架构比以细节为基础搭建的架构要稳定得多。在java中,抽象指的时接口或是抽象类,细节就是具体得实现类
5.使用接口或抽象类的目的时规定好规范,而不涉及任何具体操作,把展现细节的任务交给他们的实现类完成
依赖倒转原则的三种实现方式
1.接口传递
2.构造方法传递
3.setter方式传递
应用实例
没有使用依赖倒转原则
public class DependecyInversion {
public static void main(String[] args) {
Person p = new Person();
p.receive(new Email());
}
}
/*
* 完成Person接收消息的功能
*方式1分析
*1. 简单,比较容易想到
*2. 如果我们获取的对象是微信,短信等等,则新增类,同时Person类也要增加相应的接受方法
*3.解决思路:引入一个抽象的接口IReceiver,表示接收者,这样Person类 与接口IReceiver发生依赖
*因为Email,微信,等等属于接收的范围,他们各自实现IReceiver接口就ok了,这样我们就符合依赖倒转原则
*/
class Email{
public String getInfo() {
return "电子邮件信息:hello, world";
}
}
class Person{
public void receive(Email email) {
System.out.println(email.getInfo());
}
}
接口传递
public class DependecyInversionTest {
public static void main(String[] args) {
//方法1,通过接口实现
ChangHong changHong = new ChangHong(); //创建ChangHong类的对象
OpenAndClose openAndClose = new OpenAndClose(); //创建OpenAndClose类的对象
openAndClose.open(changHong); //通过接口实现
}
}
//方式1:通过接口传递依赖
interface IOpenAndClose {
public void open(ITV tv);
}
interface ITV {
public void play();
}
class OpenAndClose implements IOpenAndClose{
public void open(ITV tv) {
tv.play();
}
}
class ChangHong implements ITV{
public void play() {
System.out.println("打开");
}
}
构造方法传递
public class DependecyInversionTest {
public static void main(String[] args) {
//方法2,通过构造器实现
ChangHong changHong = new ChangHong(); //创建ChangHong类的对象
OpenAndClose openAndClose= new OpenAndClose(changHong); //创建OpenAndClose类的对象
openAndClose.open(); //通过构造器实现
}
}
//方式2,通过构造方法依赖传递
interface IOpenAndClose {
public void open();
}
interface ITV{
public void play();
}
class OpenAndClose{
public ITV tv;
public OpenAndClose(ITV tv) {
this.tv = tv;
}
public void open() {
this.tv.play();
}
}
class ChangHong implements ITV{
@Override
public void play() {
// TODO Auto-generated method stub
System.out.println("打开");
}
}
setter方式传递
public class DependecyInversionTest {
public static void main(String[] args) {
//方法3,通过setter方式实现
ChangHong changHong = new ChangHong(); //创建ChangHong类的对象
OpenAndClose openAndClose = new OpenAndClose(); //创建ChangHong类的对象
openAndClose.setTV(changHong); //通过setter方式传递
openAndClose.open(); //调用open()方法
}
}
//方式3,通过setter方法传递
interface IOpenAndClose{
public void open();
}
interface ITV{
public void play();
}
class ChangHong implements ITV{
public ITV tv;
public void play() {
System.out.println("打开");
}
}
class OpenAndClose implements IOpenAndClose{
public ITV tv;
public void setTV(ITV tv) {
this.tv = tv;
}
public void open() {
this.tv.play();
}
}