美文网首页
OkHttp源码责任链解析

OkHttp源码责任链解析

作者: 云木杉 | 来源:发表于2019-12-21 14:38 被阅读0次

责任链模式的运用

public interface Interceptor {

  Response intercept(Chain chain) throws IOException;

  interface Chain {
    Request request();
    Response proceed(Request request) throws IOException;
  }
}
  • 1.实例化一个Chain对象,构造器里传入拦截器的一个数组,调用proceed方法
    Interceptor.Chain chain = new RealInterceptorChain(interceptors);
    chain.proceed(....,index = 0)
  • 2.在chain的proceed()的方法中,构造一个新的Chain对象,并且获取拦截器数组的拦截器,将新构造的Chain对象传入拦截器的intercept()方法
 public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,int index) {
      
    // 这里传入的拦截器,角标加1 
    RealInterceptorChain next = new RealInterceptorChain(interceptors[index + 1], request);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);

    return response;
  }
  • 3.在拦截器的intercept方法中,调用chain.proceed()方法,将再次回到第二步中,再次实例化一个Chain对象,传入构造器数组里的index+1的拦截器,继续执行,依次类推,直到intercept数组中的拦截器执行完。最后一个Chain对象将不再执行proceed()方法。
@Override 
public Response intercept(Chain chain) {

    Reponse networkResponse = chain.proceed(networkRequest);

    return networkResponse;

}

相关文章

网友评论

      本文标题:OkHttp源码责任链解析

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