设计模式(责任链模式)

当多个对象都存在处理请求的情况时,通过构造一条处理责任链,将请求者和处理者解耦。这样具体的处理方式和处理顺序都可以灵活调整。

代码如下:

  • Handler
public abstract class Handler {
    public Handler next;
    
    public Handler setNext(Handler handler){
        this.next = handler;
        return this;
    }
    
    public abstract void doAction();
}
  • HandlerOneImpl
public class HandlerOneImpl extends Handler {

    @Override
    public void doAction() {
        if(null != this.next){
            this.next.doAction();
        }
        
        System.out.println("HandlerOneImpl");
    }
}
  • HandlerTwoImpl
public class HandlerTwoImpl extends Handler {

    @Override
    public void doAction() {
        if(null != this.next){
            this.next.doAction();
        }
        
        System.out.println("HandlerTwoImpl");
    }
}
  • APP 测试类
public class App {

    public static void main(String[] args) {
        HandlerOneImpl one = new HandlerOneImpl();
        one.setNext(new HandlerTwoImpl()).doAction();
    }
}
  • 输出结果
HandlerTwoImpl
HandlerOneImpl
原文地址:https://www.cnblogs.com/Fredric-2013/p/4572956.html