责任链模式就是很多对象由每个对象对其下家的引用而连接起来形成一条链,请求在这条链上传递,直到链上的某个对象处理此请求,或者每个对象都可以处理请求,并传给“下家”,直到最终链上每个对象都处理完
通常责任链械包括下面几个角色
1、Handler(抽象处理者):定义一个处理请求的接口
2、ConcreteHandler(具体处理者):处理请求的具体类,或者传给“下家”
Handler
package design.pattern.chainofresposibility; public abstract class Handler { private Handler nextHandler; public void setNextHandler(Handler handler) { this.nextHandler = handler; } public void handler() { this.action(); if (null != nextHandler) nextHandler.handler(); } protected abstract void action(); }
ConcreteHandlerA
package design.pattern.chainofresposibility; public class ConcreteHandlerA extends Handler { @Override protected void action() { System.out.println("ConcreteHandlerA"); } }
ConcreetHandlerB
package design.pattern.chainofresposibility; public class ConcreteHandlerB extends Handler { @Override protected void action() { System.out.println("ConcreteHandlerB"); } }
Client
package design.pattern.chainofresposibility; public class Client { public static void main(String[] args) { Handler han = new ConcreteHandlerA(); han.setNextHandler(new ConcreteHandlerB()); han.handler(); } }