责任链模式

xiaoxiao2021-02-28  35

  定义: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 chain until an object handles it.(使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止。) 抽象处理者的代码: public abstract class Handler { private Handler nextHandler; //每个处理者都必须对请求做出处理 public final Response handleMessage(Request request){ Response response = null; //判断是否是自己的处理级别 if(this.getHandlerLevel().equals(request.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); } 抽象的处理者实现三个职责: 一是定义一个请求的处理方法handleMessage,唯一对外开放的方法; 二是定义一个链的编排方法setNext,设置下一个处理者; 三是定义了具体的请求者必须实现的两个方法:定义自己能够处理的级别getHandlerLevel和具体的处理任务echo。 注意事项: 链中节点数量需要控制,避免出现超长链的情况,一般的做法是在Handler中设置一个最大节点数量,在setNext方法中判断是否已经是超过其阈值,超过则不允许该链建立,避免无意识地破坏系统性能。
转载请注明原文地址: https://www.6miu.com/read-2624645.html

最新回复(0)