【设计模式】聊聊职责链模式

原理和实现

模板模式变化的是其中一个步骤,而责任链模式变化的是整个流程。
将请求的发送和接收解耦合,让多个接收对象有机会可以处理这个请求,形成一个链条。不同的处理器负责自己不同的职责。

定义接口

public interface Filter {

    /**
     *  执行过滤方法
     * @param request
     * @param response
     * @param filterChain
     */
    void doFilter (Request request, Response response,FilterChain filterChain);
}

定义职责链
通过内部一个链表 将职责链添加到对应的链表中

public class FilterChain implements Filter{

    private static List<Filter> filterList = new LinkedList<>();

    private Filter myFilter;

    private static int filterIndex = 0;

    /**
     * 添加一个职责工作链
     * @param filter
     */
    public void addFilter (Filter filter) {
        filterList.add(filter);
    }

    public void addMyFilter (Filter filter) {
        myFilter = filter;
    }

    @Override
    public void doFilter(Request request, Response response, FilterChain filterChain) {
        if (filterIndex < filterList.size()) {
            Filter filter = filterList.get(filterIndex);
            filterIndex++;
            filter.doFilter(request,response,filterChain);
        } else {
            myFilter.doFilter(request,response,filterChain);
        }
    }
}
public class HttpFilter implements Filter{

    @Override
    public void doFilter(Request request, Response response, FilterChain filterChain) {
        System.out.println("httpFilter before...");
        filterChain.doFilter(request,response,filterChain);
        System.out.println("httpFilter after...");
    }
}
public class MyFilter implements Filter{

    @Override
    public void doFilter(Request request, Response response, FilterChain filterChain) {
        System.out.println("MyFilter before...");
        System.out.println("hahaha 我是中间执行人");
        System.out.println("MyFilter after...");
    }
}
public class EncodingFilter implements Filter{

    @Override
    public void doFilter(Request request, Response response, FilterChain filterChain) {
        System.out.println("EncodingFilter before...");
        filterChain.doFilter(request,response,filterChain);
        System.out.println("EncodingFilter after...");
    }
}
	public static void main(String[] args) {
        FilterChain filterChain = new FilterChain();

        Filter httpFilter = new HttpFilter();
        Filter encodingFilter = new EncodingFilter();
        Filter myFilter = new MyFilter();

        filterChain.addFilter(httpFilter);
        filterChain.addFilter(encodingFilter);
        filterChain.addMyFilter(myFilter);

        filterChain.doFilter(new Request(),new Response(),filterChain);

    }

其实不管是模板模式、策略模式、职责链模式 本质都是为了提高代码的拓展性、应对代码的复杂性,并且如果新增一个过滤器,那么只需要进行拓展、也满足开闭原则。

在实际的工作中,需要考虑什么场景下符合,就采用对应的设计模式,而不要乱用。

servlet中Filter就是职责链的体现。

你可能感兴趣的:(#,设计模式,设计模式,java,servlet)