定义:
- 使多个对象都有机会处理请求,从而避免了请求的发送者和接收者之间的耦合关系。将这些对象形成一条链,并沿着这条链传递该请求,直到有对象处理它为止。
通用类图:
/*
* 定义抽象的处理类
* */
public abstract class Handler {
// 根据当前设置的相关等级做出对应的处理
private Handler nextHandler;
final Response handleMessage(Request request) {
Response response = null;
// 指定不同的判断条件
if (request.getLevel().equals(this.getHandlerLevel())) {
response = this.echo(request);
} else {
if (nextHandler != null) {
response = this.nextHandler.handleMessage(request);
} else {
}
}
return response;
}
public void setNextHandler(Handler handler) {
this.nextHandler = handler;
}
// 抽象出获取等级和处理相应的方法
abstract Level getHandlerLevel();
abstract Response echo(Request request);
}
/*
* 定义请求类
* */
public class Request {
Level getLevel() {
return null;
}
}
public class Response {
// 返回的相应数据
}
/*
* 定义一个请求和处理等级
* */
public class Level {
}
public class HandlerOne extends Handler {
@Override
Level getHandlerLevel() {
// TODO Auto-generated method stub
return null;
}
@Override
Response echo(Request request) {
// TODO Auto-generated method stub
return null;
}
}
public class HandlerThree extends Handler {
@Override
Level getHandlerLevel() {
// TODO Auto-generated method stub
return null;
}
@Override
Response echo(Request request) {
// TODO Auto-generated method stub
return null;
}
}
public class HandlerTwo extends Handler {
@Override
Level getHandlerLevel() {
// TODO Auto-generated method stub
return null;
}
@Override
Response echo(Request request) {
// TODO Auto-generated method stub
return null;
}
}
public class Client {
public static void main(String[] args) {
// 创建所有可能的处理节点
HandlerOne handlerOne = new HandlerOne();
HandlerTwo handlerTwo = new HandlerTwo();
HandlerThree handlerThree = new HandlerThree();
// 设置责任连的执行顺序
handlerOne.setNextHandler(handlerTwo);
handlerTwo.setNextHandler(handlerThree);
Response response = handlerOne.handleMessage(new Request());
}
}
优点:
缺点:
- 性能问题
- 调试不便,特别是责任连较长、环节较多,由于采用了类似递归的方法,调试逻辑较复杂。
注意事项:
- 需要控制链中节点的数量,避免出现超长链的情况,通常的做法是Handler中设置最大的节点数量,在setNext方法中判断是否已经超过阈值,避免降低系统性能。