标签:
责任链模式的定义:
Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.
Chain the receiving objects and pass the request along the chaing until an object handles it;
使用多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,
知道有对象处理它为止。
//抽象处理者 public abstract class Handler{ private Handler nextHandler; public final Response handleMessage(Request request){ Resonpse response=null; if(this.getHandlerLevel().equals(requset.getRequestLevel())){ response=this.echo(request); }else{ if(this.nextHandler !=null){ response=this.nextHandler.handleMessage(request); }else{ //..... } } return response; } public void setNext(Handler _handler){ this.nextHandler=_handler; } protected abstract Level getHandlerLevel(); protected abstract Response echo(Request request); } //具体处理者 public class ConcreteHandler1 extends Handler{ protected Response echo(Request request){ return null; } protected Level getHandlerLevel(){ return null; } } public class ConcreteHandler2 extends Handler{ protected Response echo(Request request){ return null; } protected Level getHandlerLevel(){ return null; } } public class ConcreteHandler3 extends Handler{ protected Response echo(Request request){ return null; } protected Level getHandlerLevel(){ return null; } } public class Level{} public class Request{} public class Response{} //场景类 public class Client{ public static void main(String[] args){ Handler handler1=new ConcreteHanlder1(); Handler handler2=new ConcreteHanlder2(); Handler handler3=new ConcreteHanlder3(); handler1.setNext(hanlder2); handler2.setNext(handler3); Response response=handler1.handlerMessage(new Request()); } }
责任链模式优点:将请求和处理分开。请求者可以不用知道是谁处理的,处理者可以不用知道请求的全貌
缺点:一是性能问题,每个请求都是从链头遍历到链尾,特别是链比较长时,性能是一个非常大的问题
二是调试不很方便,特别是链比较长时
注意事项:链中节点数量要控制,避免出现超长链的情况,一般的做法是在Handler中设置一个最大的节点数量,在setNext方法
中判断是否已经超过其阈值,超过则不允许该链建立,避免无意识的破坏系统性能
标签:
原文地址:http://www.cnblogs.com/liaojie970/p/5485810.html