责任链模式(Chain of Responsibility Pattern)在众多的框架中使用的非常普遍,例如SpringMVC、SpringSecurity等。责任链模式就是要将执行的逻辑串联起来,同时可以随时在链中的某一节点结束。那么下面用简短的代码来实现该模式
public class FilterChainTest {
/**
* 1,定义一个链的抽象
* */
interface Chain{
void doFilter(String request,String response) ;
}
/**
* 2,定义一个用于处理具体业务逻辑的接口
* */
interface Filter {
void doFilter(String request,String response,Chain chain);
}
/**
* 实现自定义的链
* */
public static class MyChain implements Chain{
private List<Filter> filters ;
private Iterator<Filter> iterator ;
public MyChain(List<Filter> filters){
this.filters = filters ;
iterator = filters==null?null:filters.listIterator() ;
}
/**
* 执行责任链中保存的Filter实例。
* 是否要继续执行链上后续的Filter由具体的Filter决定【当然这只是一种策略,还可以
* 根据返回值来判断是否要继续执行后续的Filter等】
* */
@Override
public void doFilter(String request, String response) {
if(iterator == null || !iterator.hasNext()){
return;
}
iterator.next().doFilter(request,response,this);
}
}
public static class MyFilter implements Filter{
private String msg ;
public MyFilter(String msg){
this.msg = msg ;
}
@Override
public void doFilter(String request, String response, Chain chain) {
System.out.println("hello " + msg);
//继续执行调用链后面的Filter
chain.doFilter(request,response);
System.out.println("finish " + msg);
}
}
public static void main(String[] args){
//创建多个Filter,并放入到集合
MyFilter filter1 = new MyFilter("first") ;
MyFilter filter2 = new MyFilter("second") ;
MyFilter filter3 = new MyFilter("third") ;
List<Filter> filterList = new ArrayList<>() ;
filterList.add(filter1) ;
filterList.add(filter2) ;
filterList.add(filter3) ;
//构造责任链对象,并开始执行
MyChain myChain = new MyChain(filterList) ;
myChain.doFilter("request","response");
}
}
执行后的打印结果
hello first
hello second
hello third
finish third
finish second
finish first