标签:加班 面向 要求 nts 存在 chat depend ati worker
依赖倒转原则,又称依赖倒置原则(Dependence Inversion Principle),又称DIP原则
上层模块不应该依赖底层模块,它们都应该依赖于抽象
抽象不应该依赖于细节,细节应该依赖于抽象
换句话说,依赖倒转原则 核心的理念 相对于细节来说,抽象要稳定得多。就是要求我们要面向接口编程。
抽象类和接口 价值? 设计
package DependenceInversionPrinciple;
public class InversionDemo {
public static void main(String[] args) {
new Worker().getMessage(new DingDing());
new Worker().getMessage(new WeChat());
new Worker().getMessage(new Message());
}
}
interface IMessage {
void sendMessage();
}
class Worker {
public void getMessage(IMessage iMessage) {
iMessage.sendMessage();
}
}
class DingDing implements IMessage {
@Override
public void sendMessage() {
System.out.println("钉钉上,老板找你加班了");
}
}
class WeChat implements IMessage {
@Override
public void sendMessage() {
System.out.println("钉钉不回,老板给你打微信电话了");
}
}
class Message implements IMessage {
@Override
public void sendMessage() {
}
}
依赖倒转原则本质上,就是通过抽象(抽象类和接口)使得各个类或者模块实现彼此独立,互不影响,实现模块间松耦合,要先顶层再细节的方式来进行代码设计
//假设消息规范
interface IMessage2{
void sendMessage(Produce produce);
}
//消息真正的生产者
interface Produce{
void produceMessage();
}
class Worker2 implements IMessage2 {
@Override
public void sendMessage(Produce produce) {
produce.produceMessage();
}
}
interface IMessage2{
void sendMessage(Produce produce);
}
//消息真正的生产者
interface Produce{
void produceMessage();
}
class Worker2 implements IMessage2 {
public Produce produce;
public Worker2(Produce produce){
this.produce = produce;
}
@Override
public void sendMessage(Produce produce) {
produce.produceMessage();
}
}
interface IMessage2 {
void sendMessage(Produce produce);
}
//消息真正的生产者
interface Produce {
void produceMessage();
}
class Worker2 implements IMessage2 {
public Produce produce;
public void setProduce(Produce produce) {
this.produce = produce;
}
@Override
public void sendMessage(Produce produce) {
produce.produceMessage();
}
}
标签:加班 面向 要求 nts 存在 chat depend ati worker
原文地址:https://www.cnblogs.com/stu-jyj3621/p/14668621.html