23种设计模式之责任链模式
责任链模式(Chain Of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
package designMode.chainOfResponsibility; abstract class Handler { protected Handler successor; public void setSuccessor(Handler successor) { this.successor = successor; } public abstract void handleRequest(int request); }
package designMode.chainOfResponsibility; class ConcreteHandler1 extends Handler{ @Override public void handleRequest(int request) { if(request>=0 && request<10) System.out.println("处理0到9的请求!"); else if(successor != null) successor.handleRequest(request); } } class ConcreteHandler2 extends Handler{ @Override public void handleRequest(int request) { if(request>=10 && request<20) System.out.println("处理10到19的请求!"); else if(successor != null) successor.handleRequest(request); } } class ConcreteHandler3 extends Handler{ @Override public void handleRequest(int request) { if(request>=20 && request<30) System.out.println("处理20到29的请求!"); else if(successor != null) successor.handleRequest(request); } }
package designMode.chainOfResponsibility; class Test { public static void main(String[] args) { Handler h1 = new ConcreteHandler1(); Handler h2 = new ConcreteHandler2(); Handler h3 = new ConcreteHandler3(); h1.setSuccessor(h2); h2.setSuccessor(h3); int[] requests = {2,5,14,22,18,3,27,20}; for (int i : requests) { h1.handleRequest(i); } } }