Java设计模式<责任链>
意图
- 避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止
场景
- 处理消息的时候以过滤很多道
优点
- 降低耦合度。它将请求的发送者和接收者解耦
- 简化了对象。使得对象不需要知道链的结构
- 增强给对象指派职责的灵活性。通过改变链内的成员或者调动它们的次序,允许动态地新增或者删除责任
- 增加新的请求处理类很方便
现实场景举例
JavaDemo
审批人接口
public abstract class Worker {
protected Worker worker;
public abstract void permit();
public Worker setNext(Worker next){
this.worker = next;
return next;
}
}
Team Leader
public class TLWorker extends Worker{
public void permit() {
System.err.println("i am the TL ,I have permitted ");
if(worker != null){
worker.permit();
}
}
}
PM
public class PMWorker extends Worker {
public void permit() {
System.err.println("i am the PM ,I have permitted ");
if(worker != null){
worker.permit();
}
}
}
CEO
public class CEOWorker extends Worker {
public void permit() {
System.err.println("i am the CEO ,I have permitted ");
if(worker != null){
worker.permit();
}
}
}
测试类
public class DemoMain {
public static void main(String[] args) {
CEOWorker ceoWorker = new CEOWorker();
PMWorker pmWorker = new PMWorker();
TLWorker tlWorker = new TLWorker();
tlWorker.setNext(pmWorker).setNext(ceoWorker);
tlWorker.permit();
}
}
输出
i am the TL ,I have permitted
i am the PM ,I have permitted
i am the CEO ,I have permitted