职责链模式例子

 

public interface Filter {
    void doFilter(Request request,Response response,FilterChain fc);
}

 

public class FirstFilter implements Filter {

    @Override
    public void doFilter(Request request, Response response,FilterChain fc) {
        request.requestStr+="---FirstFilter";
        fc.doFilter(request, response, fc);
        response.responseStr+="---FirstFilter";
    }
}

 

public class SecondFilter implements Filter {

    @Override
    public void doFilter(Request request, Response response,FilterChain fc) {
        request.requestStr+="---SecondFilter";
        fc.doFilter(request, response, fc);
        response.responseStr+="---SecondFilter";
    }
}

 

 

public class FilterChain implements Filter {
    List<Filter> list = new ArrayList<Filter>();
    int index = 0;

    public void putChain(Filter filter) {
        list.add(filter);
    }

    @Override
    public void doFilter(Request request, Response response, FilterChain fc) {
        if (index == list.size())
            return;

        Filter filter = list.get(index);
        index++;
        filter.doFilter(request, response, fc);
    }
}

 

 

public class Request {
    public String requestStr="request:";
}

 

public class Response {
    public String responseStr="response:";
}

 

 

public static void main(String[] args) {
         
        Request request=new Request();
        Response response=new Response();
        FilterChain fc=new FilterChain();
        SecondFilter f2=new SecondFilter();
        FirstFilter f1=new FirstFilter();
        fc.putChain(f1);
        fc.putChain(f2);
        fc.doFilter(request, response,fc);
        System.out.println(request.requestStr);
        System.out.println(response.responseStr);
    }

 

输出结果如下:

request:---FirstFilter---SecondFilter
response:---SecondFilter---FirstFilter

 

posted @ 2018-10-09 20:10  叶de第柒章  阅读(333)  评论(0编辑  收藏  举报