一、介绍
职责链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
接收者和发送者都没有对方的明确信息,且链中的对象自己也并不知道链的结构。结果是职责链可简化对象的相互连接,它们仅需保持一个指向其后继者的引用,而不需保持它所有的候选接受者的引用。
随时地增加或修改处理一个请求的结构。增强了给对象指派职责的灵活性。
二、代码实现
public abstract class Handler { //继任者 protected Handler successor; //设置继任者 public void setSuccessor(Handler successor) { this.successor = successor; } public abstract void handleRequest(int request); } public class ConcreteHandler1 extends Handler { @Override public void handleRequest(int request) { if (request >= 0 && request < 10) { System.out.println(this.getClass().getSimpleName() + "处理请求:" + request); } else if (successor != null) { successor.handleRequest(request); } else { throw new RuntimeException("error"); } } } public class ConcreteHandler2 extends Handler { @Override public void handleRequest(int request) { if (request >= 10 && request < 20) { System.out.println(this.getClass().getSimpleName() + "处理请求:" + request); } else if (successor != null) { successor.handleRequest(request); } else { throw new RuntimeException("error"); } } } public class ConcreteHandler3 extends Handler { @Override public void handleRequest(int request) { if (request >= 20 && request < 30) { System.out.println(this.getClass().getSimpleName() + "处理请求:" + request); } else if (successor != null) { successor.handleRequest(request); } else { throw new RuntimeException("error"); } } }
测试
public class Client { public static void main(String[] args) { Handler h1 = new ConcreteHandler1(); Handler h2 = new ConcreteHandler2(); Handler h3 = new ConcreteHandler2(); h1.setSuccessor(h2); h2.setSuccessor(h3); int[] requests = {2, 10, 9, 15, 55, 21}; for (int request : requests) { h1.handleRequest(request); } } }