一、简介
责任链模式(Chain of Responsibility Pattern)是一种行为设计模式,它允许多个对象有机会处理一个请求。请求沿着处理者链传递,直到某个处理者决定处理此请求。
二、技术实现
2.1 Handler
java
public interface Handler{
void handle(Request req, Response resp, Chain chain);
}
2.2 Chain
java
public class Chain{
private List<Handler> handlers;
private int index;
public Chain(List<Handler> handlers){
this.handlers = handlers;
}
public void next(Request req, Response resp){
if (index + 1 < handlers.size()){
handlers.get(index++).handle(req, resp, this);
}
}
}
2.3 Handler 实现
java
public LogHandler implements Handler{
@Override
public void Handle (Request req, Response resp, Chain chain){
long start = System.currentTimeStamps();
chain.next(req,resp);
log.info("request:{},response:{}, duration:{}",req, resp, System.currentTimeStamps() - start);
}
}