责任链模式

2018-06-10  本文已影响7人  Il_mondo

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

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(){
        ...
    }
}
上一篇下一篇

猜你喜欢

热点阅读