美文网首页
责任链模式

责任链模式

作者: Il_mondo | 来源:发表于2018-06-10 15:54 被阅读7次

    使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有对象处理它为止

    public class Request {
        public Object body(){
            return null;
        }
    
        public Map<String, String> header(String key, String value){
            return null,
        }
    
        public Request newBuilder(){
            return new Build();
        }
    }
    
    public class Response {
        private Map<String, String> heads;
    }
    
    public interface Interceptor {
        Response intercept(Interceptor.Chain chain);
    
        interface Chain {
            Request request();
            Response proceed(Request request);
        }
    }
    
    public class NetworkInterceptorChain implements Interceptor.Chain{
        private int index;
        private Request request;
        private List<Interceptor> interceptors;
    
        public NetworkInterceptorChain(Request request, List<Interceptor> interceptors, int index){
            this.index = index;
            this.request = request;
            this.interceptors = interceptors;
        }
    
        @Overrdie
        public Response proceed(Request request){
            if(interceptors.size() > index){
                NetworkInterceptorChain chain = new NetworkInterceptorChain(index + 1, request);
                Interceptor interceptor = interceptors.get(index);
                Response interceptedResponse = interceptor.intercept(chain);
    
                if(interceptedResponse == null){
                    throw new NullPointerException();
                }
    
                return interceptedResponse;
            }
    
            Response response = readNetworkResponse();
            return response;
        }
    
        @Override
        public Request request(){
            ...
        }
    
        public Response readNetworkResponse(){
            ...
        }
    }
    

    相关文章

      网友评论

          本文标题:责任链模式

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