一、责任链模式的定义
定义如下:
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);
}
}
return response;
}
public void setNext(Handler handler) {
this.nextHandler = handler;
}
protected abstract Level getHandlerLevel();
protected abstract Response echo(Request request);
}
抽象处理者实现三个职责:一是定义一个请求的处理方法handleMessage,唯一对我I啊开放的方法;而是定义一个链的编排方法setNext,设置下一个处理者;三是定义了具体的请求者必须实现的两个方法:定义自己能够处理的级别getHandlerLevel和具体的处理任务echo
具体的三个处理者:
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;
}
}
在处理者中设计三个类:Level类负责定义请求和处理级别,Request负责封装请求,Response负责封装链中返回的结果,这三个类都需要根据业务产生,读者可以在实际应用中完成相关的业务填充
public class Level {
}
public class Request {
//请求的等级
public Level getRequestLevel() {
return null;
}
}
public class Response {
}
场景类:
public class Client {
public static void main(String args[]) {
Handler handler1 = new ConcreteHandler1();
Handler handler2 = new ConcreteHandler2();
Handler handler3 = new ConcreteHandler3();
handler1.setNext(handler2);
handler2.setNext(handler3);
Response response = handler1.handleMessage(new Request());
}
}
二、责任链模式的优缺点
优点:
责任链模式非常显著的优点是将请求和处理分开。请求者可以不用知道是谁处理的,处理者可以不用知道请求的全貌,两者解耦,提高系统的灵活性
缺点:
责任链有两个非常显著的缺点:一是性能问题,每个请求都是从链头遍历到链尾,特别是链比较长的时候,性能是一个非常大的问题。二是调试不很方便,特别是链条比较长,环节比较多的时候,由于采用了类似递归的方式,调试的时候逻辑可能比较复杂。