责任链模式定义:
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 class Level { // 定义一个请求和处理等级 }
请求类:
public class Request { // 请求的等级 public Level getRequestLevel() { return null; } }
返回结果类:
public class Response { // 处理者返回的数据 }
核心:Handler抽象类:
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 { // 如果不是自己的处理级别,传递下去,如果下一个处理者没有,直接返回null if (this.nextHandler != null) { response = this.nextHandler.handleMessage(request); } else { System.out.println("没有适当的处理者,业务处理不了,返回null"); } } return response; } //设置下一个处理者 public void setNextHandler(Handler _nextHandler) { this.nextHandler = _nextHandler; } // 每个处理者都有一个处理级别 protected abstract Level getHandlerLevel(); // 每个处理者都必须实现处理逻辑 protected abstract Response echo(Request request); }
具体的几个Handler实现类:
public class ConcreteHandler1 extends Handler { @Override protected Level getHandlerLevel() { // 设置自己的处理级别 return null; } @Override protected Response echo(Request request) { // 完成具体的业务逻辑 return null; } }
public class ConcreteHandler2 extends Handler { @Override protected Level getHandlerLevel() { // 设置自己的处理级别 return null; } @Override protected Response echo(Request request) { // 完成具体的业务逻辑 return null; } }
public class ConcreteHandler3 extends Handler { @Override protected Level getHandlerLevel() { // 设置自己的处理级别 return null; } @Override protected Response echo(Request request) { // 完成具体的业务逻辑 return null; } }
最后客户端调用演示类:
public class Client { public static void main(String[] args) { // 声明所有的处理节点 Handler handler1= new ConcreteHandler1(); Handler handler2= new ConcreteHandler1(); Handler handler3= new ConcreteHandler1(); // 设置责任链中的链接顺序 handler1.setNextHandler(handler2); handler2.setNextHandler(handler3); // 提交请求,返回结果 Response response = handler1.handleMessage(new Request()); } }
责任链模式优点:
将请求和处理分开,请求者不用知道是谁处理的,处理者也不用知道请求的全貌,两者解耦,提高系统的灵活性。
责任链模式的缺点:
第一个是性能问题,每个请求都是从链头遍历到链尾,特别是链比较长的时候性能是个很大问题
第二个是调试不方便,类似于递归调用,调试非常不方便
责任链模式注意事项:
一般做法是Handler中设置1个最长节点数量,在setNext方法中判断是否超过阈值,超过了就不允许该链建立,避免破坏系统性能。
本人博客已搬家,新地址为:http://yidao620c.github.io/