责任链模式:根据一条链路执行代码
以下代码逻辑:
ABC 三个filter
处理request 时,执行链条为 A->B->C
处理reponse时,执行链条为 C->B->A
实现思路:递归
public class FilterChainDemo {
public static void main(String[] args) {
String request = "request";
String response = "response";
Filter filter = new HtmlFilter();
Filter filter1 = new UrlFilter();
FilterChain filterChain = new FilterChain().addFilter(filter).addFilter(filter1).addFilter(new ThreeFilter());
filterChain.doFilter(request, response);
}
}
class FilterChain {
List<Filter> filterList = Lists.newArrayList();
// 通过 index 指定下一个要执行的filter
int index = 0;
public FilterChain addFilter(Filter filter) {
filterList.add(filter);
return this;
}
public void doFilter(String request, String response) {
if (index >= filterList.size()) {
return;
}
Filter filter = filterList.get(index);
// index++ 需要放到 doFilter 之前,否则递归会栈溢出
index++;
filter.doFilter(request, response, this);
}
}
interface Filter {
void doFilter(String request, String response, FilterChain filterChain);
}
class HtmlFilter implements Filter {
@Override
public void doFilter(String request, String response, FilterChain filterChain) {
System.out.println(request + ":HtmlFilter");
// filterChain.doFilter 开始递归,放在处理response 之前,request处理之后才开始处理response
filterChain.doFilter(request, response);
System.out.println(response + ":HtmlFilter");
}
}
class UrlFilter implements Filter {
@Override
public void doFilter(String request, String response, FilterChain filterChain) {
System.out.println(request + ":UrlFilter");
// filterChain.doFilter 开始递归,放在处理response 之前,request处理之后才开始处理response
filterChain.doFilter(request, response);
System.out.println(response + ":UrlFilter");
}
}
class ThreeFilter implements Filter {
@Override
public void doFilter(String request, String response, FilterChain filterChain) {
System.out.println(request + ":ThreeFilter");
// filterChain.doFilter 开始递归,放在处理response 之前,request处理之后才开始处理response
filterChain.doFilter(request, response);
System.out.println(response + ":ThreeFilter");
}
}