前面讨论了创建型模式、结构型模式,今天我们来讨论一下行为型模式。责任链模式,就是我们讨论的第一种行为型模式。责任链模式具体不容易说出来,但是如果看一看责任链模式的实际例子就很容易明白了。最典型的例子就是Java EE Servlet中的过滤器,以链式方式对请求进行过滤了。当我们遇到类似需求的时候,也可以使用责任链模式来解决。
下面我们来模拟一下Java Servlet中的Filter。首先,需要请求和响应的接口和实现。这两个接口都很简单。
//请求
public interface Request {
String getMessage();
}
class RequestImpl implements Request{
private String msg;
public RequestImpl(String msg) {
this.msg = msg;
}
@Override
public String getMessage() {
return msg;
}
}
//响应
public interface Response {
String getMessage();
}
class ResponseImpl implements Response {
private String msg;
public ResponseImpl(String msg) {
this.msg = msg;
}
@Override
public String getMessage() {
return msg;
}
}
之后是过滤器的接口和实现。过滤器将会对请求和处理进行处理和过滤。过滤器1和2是正常的过滤器,过滤之后还会继续调用链上的其它过滤器。而过滤器3则会直接阻断链。
public interface Filter {
void doFilter(Request request, Response response, FilterChain chain);
}
class FilterImpl1 implements Filter {
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
System.out.println("In filter1: " + request.getMessage() + ":" + response.getMessage());
chain.doFilter(request, response);
}
}
class FilterImpl2 implements Filter {
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
System.out.println("In filter2: " + request.getMessage() + ":" + response.getMessage());
chain.doFilter(request, response);
}
}
class FilterImpl3 implements Filter {
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
System.out.println("In filter3: " + request.getMessage() + ":" + response.getMessage());
}
}
下面来实现责任链。责任链其实和很简单,开始过滤之后,责任链就会不断的调用链上的过滤器,直到某个过滤器判断不需要继续过滤(例如过滤器3)或者链到头为止。为了让这个链能够复用,我还添加了当前调用链的标记current,标记调用到哪里了,再到头之后重新将current设置为0。
class FilterChain {
private List<Filter> filters;
private int current;
public FilterChain(List<Filter> filters) {
this.filters = filters;
current = 0;
}
void doFilter(Request request, Response response) {
if (current <= filters.size() - 1) {
Filter currentFilter = filters.get(current);
current++;
currentFilter.doFilter(request, response, this);
} else {
current = 0;
}
}
}
这样一个责任链就完成了。我们来调用一下。
public void run() {
Filter filter1 = new FilterImpl1();
Filter filter2 = new FilterImpl2();
List<Filter> filters = new ArrayList<>();
filters.add(filter1);
filters.add(filter2);
FilterChain chain = new FilterChain(filters);
Request request = new RequestImpl("request1");
Response response = new ResponseImpl("response1");
chain.doFilter(request, response);
System.out.println();
filters.add(0,new FilterImpl3());
chain.doFilter(request, response);
}
结果应该类似这样。和我们的预期相同。
责任链模式
In filter1: request1:response1
In filter2: request1:response1
In filter3: request1:response1