美文网首页
责任链模式

责任链模式

作者: 尉昌达 | 来源:发表于2020-06-14 21:56 被阅读0次
    public class Servlet_Main {
        public static void main(String[] args) {
            Request request = new Request();
            request.str = "大家好:),<script>,欢迎访问 mashibing.com ,大家都是996 ";
            Response response = new Response();
            response.str = "response";
    
            FilterChain chain = new FilterChain();
            chain.add(new HTMLFilter()).add(new SensitiveFilter());
            chain.doFilter(request, response);
            System.out.println(request.str);
            System.out.println(response.str);
    
        }
    }
    
    interface Filter {
        void doFilter(Request request, Response response, FilterChain chain);
    }
    
    class HTMLFilter implements Filter {
        @Override
        public void doFilter(Request request, Response response, FilterChain chain) {
            request.str = request.str.replaceAll("<", "[").replaceAll(">", "]") + "HTMLFilter()";
            chain.doFilter(request, response);
            response.str += "--HTMLFilter()";
    
        }
    }
    
    class Request {
        String str;
    }
    
    class Response {
        String str;
    }
    
    class SensitiveFilter implements Filter {
        @Override
        public void doFilter(Request request, Response response, FilterChain chain) {
            request.str = request.str.replaceAll("996", "955") + " SensitiveFilter()";
            chain.doFilter(request, response);
            response.str += "--SensitiveFilter()";
    
        }
    }
    
    
    class FilterChain {
        List<Filter> filters = new ArrayList<>();
        int index = 0;
    
        public FilterChain add(Filter f) {
            filters.add(f);
            return this;
        }
    
        public void doFilter(Request request, Response response) {
            if(index == filters.size()) return;
            Filter f = filters.get(index);
            index ++;
    
            f.doFilter(request, response, this);
        }
    }
    
    filter

    运行结果:

    大家好:),[script],大家都是955 HTMLFilter() SensitiveFilter()
    response--SensitiveFilter()--HTMLFilter()
    
    

    相关文章

      网友评论

          本文标题:责任链模式

          本文链接:https://www.haomeiwen.com/subject/hggfxktx.html