1. 概念
- 高层模块不应该依赖底层模块,二者都应该依赖其抽象
- 抽象不应该依赖细节,细节应该依赖抽象
- 依赖倒转(倒置)的中心思想是面向接口编程
- 依赖倒转原则是基于这样的设计理念:相对于细节的多变性,抽象的东西要稳定的多。以抽象为基础搭建的架构比以细节为基础的架构要稳定的多。在java中,抽象指的是接口或抽象类,细节就是具体的实现类
- 使用接口或抽象类的目的是制定好规范,而不涉及任何具体的操作,把展现细节的任务交给他们的实现类去完成
2. 传递方式
3. 代码示例
3.1 需求:完成Person接收消息的功能
示例1
- 示例1代码简答:
- 简单,比较容易想到
- 如果我们获取的对象是微信,短信等等,则新增类,同时Person也要增加对应的接收方法
- 解决思路:
- 引入一个抽象的接口IReceiver,表示接收者,这要Person类与接口IReceiver发生依赖
- 原因:因为 Email, WeiXin 等等属于接收的范围,他们各自实现IReceiver接口即可,这样我们就符合依赖倒转原则
package com.bz.design.principle.inversion;
public class DependenceInversion {
public static void main(String[] args) {
Person person = new Person();
person.receive(new Email());
}
}
class Email {
public String getInfo() {
return "hello world";
}
}
class Person {
public void receive(Email email) {
System.out.println(email.getInfo());
}
}
示例2
package com.bz.design.principle.inversion;
public class DependenceInversion02 {
public static void main(String[] args) {
Person02 person = new Person02();
person.receive(new Email02());
person.receive(new WeiXin02());
}
}
class Email02 implements IReceiver {
@Override
public String getInfo() {
return "Email: hello world";
}
}
class WeiXin02 implements IReceiver {
@Override
public String getInfo() {
return "WeiXin: hello world";
}
}
class Person02 {
public void receive(IReceiver receiver) {
System.out.println(receiver.getInfo());
}
}
interface IReceiver {
String getInfo();
}
示例3
- 通过代码实现电视打开功能(三种传递方式)
- 方式1:通过接口传递实现依赖
- 方式2:通过构造方法依赖传递
- 方式3:通过setter方法传递
package com.bz.design.principle.inversion;
public class DependenceInversion03 {
public static void main(String[] args) {
OpenAndClose3 openAndClose = new OpenAndClose3();
openAndClose.setITV(new XiaoMi());
openAndClose.open();
}
}
interface IOpenAndClose {
void open(ITV tv);
}
interface ITV{
void play();
}
class OpenAndClose implements IOpenAndClose {
@Override
public void open(ITV tv) {
tv.play();
}
}
class ChangHong implements ITV{
@Override
public void play() {
System.out.println("长虹电视机打开");
}
}
interface IOpenAndClose2 {
void open();
}
interface ITV2 {
void play();
}
class OpenAndClose2 implements IOpenAndClose2 {
private ITV2 itv2;
public OpenAndClose2(ITV2 itv2) {
this.itv2 = itv2;
}
@Override
public void open() {
this.itv2.play();
}
}
class HaiEr implements ITV2 {
@Override
public void play() {
System.out.println("海尔电视机打开...");
}
}
interface IOpenAndClose3 {
void open();
void setITV(ITV3 itv3);
}
interface ITV3 {
void play();
}
class OpenAndClose3 implements IOpenAndClose3 {
private ITV3 itv3;
@Override
public void setITV(ITV3 itv3) {
this.itv3 = itv3;
}
@Override
public void open() {
this.itv3.play();
}
}
class XiaoMi implements ITV3 {
@Override
public void play() {
System.out.println("小米电视机打开...");
}
}
4. 注意事项与细节
- 低层模块尽量都要有抽象类或接口,或者两者都有,程序稳定性更好
- 变量的声明类型尽量是抽象类或接口,这样我们的变量引用和实际对象间,就存在一个缓冲层,利于程序扩展和优化
- 继承时遵循里氏替换原则