职责链模式的作用在于职责转移,其实现实际上是一个链表
package chainofres; public abstract class Handler { protected Handler successor; public abstract void action(int request); public void setSuccessor(Handler successor) { this.successor = successor; } } package chainofres; public class ConcurrentHandler1 extends Handler { @Override public void action(int request) { if (request < 100) System.out.println("Handler1 handle this"); else if (this.successor != null) this.successor.action(request); } } package chainofres; public class ConcurrentHandler2 extends Handler { @Override public void action(int request) { if (request >= 100 && request < 1000) System.out.println("Handler2 handle this"); else if (this.successor != null) this.successor.action(request); } } package chainofres; public class ConcurrentHandler3 extends Handler { @Override public void action(int request) { if (request >= 1000) System.out.println("Handler3 handle this"); else if (this.successor != null) this.successor.action(request); } } package chainofres; public class Client { public static void main(String[] args) { Handler h1 = new ConcurrentHandler1(); Handler h2 = new ConcurrentHandler2(); Handler h3 = new ConcurrentHandler3(); h1.setSuccessor(h2); h2.setSuccessor(h3); int request = 50; h1.action(request); request = 200; h1.action(request); request = 1500; h1.action(request); } }