Title

责任链模式

目的: 将多个对象组成一条职责链,按照职责链的顺序一个个找出谁负责处理,弱化请求方和处理方之间的关联关系,让双方都成为可独立复用的组件

使用责任链提高程序灵活性,但也可能会导致处理延迟,如果请求者和处理者之间的关系是确定的,而且需求非常快的处理速度,不使用 chain of Responsibility

 

demo1:

package app;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

public class App {
    public static void main(String[] args) throws Exception {
     
       String res = new Handler(
           Arrays.asList(             
                  x -> x.replace("script", "******"),
                  x -> x.replace("fuck", "love"),
                  x -> x.replace("hate","love")     
           )
       ).doFilter("<script>: alert(fuck java,hate you)  ");
       System.out.println(res);

    } 

    static class Handler {
        public Handler(List<Function<String,String>> filters) {
            this.filterChain = filters;
        }

        
        List<Function<String,String>> filterChain;
        public String doFilter(String res) {
            for(Function<String,String> f:filterChain) {
                res =  f.apply(res);
            } 
            
            return res;
        }
    }
     
}

 

 

对代码进行改造,一条责任链可以合并另一条责任链:

package app;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

public class FilterChain {
    public static void main(String[] args) throws Exception {
        
        Handler handler = new Handler();
        handler.addFilterChain(x->x.replace("hate", "love"));
        Handler anotherChain = new Handler(
            Arrays.asList(
                str -> str.replace("script", "***"),
                str -> str.replace("-","*")
            )
        );
        handler.addFilterChain(anotherChain);

        String res = handler.doFilter("<script> -- hate java,hate you");
        System.out.println(res);

    } 

    /**
     *  implements Function<String,String>
     *  又使用了 装饰者模式,重新包装
     */
     
    static class Handler implements Function<String,String>{
        public Handler(List<Function<String,String>> filters) {
            this.filterChain = filters;
        }
        public Handler() {
            this.filterChain = new ArrayList<>();
        }
        public void addFilterChain(Function<String,String> filterChain) {
            this.filterChain.add(filterChain);
        }
        List<Function<String,String>> filterChain;
        public String doFilter(String res) {
            for(Function<String,String> f:filterChain) {
                res =  f.apply(res);
            } 
            
            return res;
        }

        @Override
        public String apply(String res) {
            return doFilter(res);
        }
    }
     
}

 

 

代码3, 模仿 java 过滤器的 责任链:

package app;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        FilterChain filterChain = new FilterChain();
        filterChain.addFilters(new Filter() {
            @Override
            public void doFilter(Request req,Response resp,FilterChain chain) {
                req.msg+="1";
                chain.doFilter(req, resp,chain);
                resp.msg+="1";
            }
        },
        (req,resp,chain)->{
            req.msg += "2";
            chain.doFilter(req, resp,chain);
            resp.msg += "2";
        }
        
        );
        Request r = new Request();
        Response r2 = new Response();
        filterChain.doFilter(r, r2);
        System.out.println(r+"  "+r2);
       
         
    }

    @FunctionalInterface
    static interface Filter {
        void doFilter(Request request,Response response,FilterChain chain);
    }
    static class FilterChain implements Filter {
        int index = 0;
        List<Filter> delegates;
        public FilterChain() {
            this.delegates = new ArrayList<>();
        }
        public FilterChain addFilters(Filter filters) {
            this.delegates.add(filters);
            return this;
        }
        public FilterChain addFilters(Filter... filters) {
            this.delegates.addAll(Arrays.asList(filters));
            
            return this;
        }

        public FilterChain addFilters(List<Filter> filters) {
            this.delegates.addAll(filters);
            return this;
        }
        
        @Override
        public void doFilter(Request request, Response response, FilterChain chain) {
             if(index>=delegates.size()) return;
             delegates.get(index++).doFilter(request, response, chain);
             
        }
        public void doFilter(Request req,Response resp) {
            doFilter(req, resp,this);
        }

    }

    static class Request {
        String msg="";

        @Override
        public String toString() {
            return "Request [msg=" + msg + "]";
        }

          

        
        
        
    }
    static class Response {
        String msg="";

        @Override
        public String toString() {
            return "Response [msg=" + msg + "]";
        }
    }
}

 

posted @ 2020-03-18 01:43  .geek  阅读(188)  评论(0编辑  收藏  举报