美文网首页
从OKHttp源码中看责任链模式

从OKHttp源码中看责任链模式

作者: lclandld | 来源:发表于2020-03-07 11:09 被阅读0次

上篇文章简单理解责任链模式只做了Demo,这篇文章就结合OKHttp的框架来具体看看责任链模式,没看过上篇文章的建议可以看看,尤其是第四点优化代码那一块。

一个框架中往往会涉及到很多的设计模式,在OKHttp中用到责任链模式的是拦截器Interceptor,因为只是对责任链模式的源码分析,所有我会省略掉那些影响我们看源码的部分。

一、OkHttp框架中的Interceptor是如何使用责任链模式的

1、OKHttp的一个简单应用入口
    @Test
    public void test(){
        try{
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://www.baidu.com/")
                    .build();
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            System.out.println(response.body().string());
        }catch (Exception e){
        }
    }
2、关键性源码分析
client.newCall(request),实例化了一个RealCall
 @Override public Call newCall(Request request) {
    return new RealCall(this, request, false /* for web socket */);
  }
client.newCall(request).execute() ,直接看RealCall中的execute()方法
  @Override public Response execute() throws IOException {
      ...
      Response result = getResponseWithInterceptorChain();
      ...
getResponseWithInterceptorChain(),执行拦截器
  • 责任链模式的Client
 Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
   //第一步:把对应的五个拦截器都放入到interceptors List中
    interceptors.addAll(client.interceptors());
    interceptors.add(retryAndFollowUpInterceptor);
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    interceptors.add(new CacheInterceptor(client.internalCache()));
    interceptors.add(new ConnectInterceptor(client));
    if (!forWebSocket) {
      interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(forWebSocket));
    //第二步:把所有的具体处理者链接起来
    Interceptor.Chain chain = new RealInterceptorChain(
        interceptors, null, null, null, 0, originalRequest);
    //第三步:开始处理
    return chain.proceed(originalRequest);
  }

上面的代码和下面的这个截图是不是一样的(有不懂的童鞋,请看上篇简单理解责任链模式)


简单理解责任链模式4-Client
  • 真实的链接类
public final class RealInterceptorChain implements Interceptor.Chain {
  private final List<Interceptor> interceptors;
  private final int index;
  ...

  public RealInterceptorChain(List<Interceptor> interceptors, int index) {
    this.interceptors = interceptors;
    this.index = index;
  }

  public Response proceed(...) {
    if (index >= interceptors.size()) throw new AssertionError();
    ...
    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(
        interceptors, index + 1);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);
    ....
    return response;
  }
}

源码中index的值是从构造方法中传入的,追溯上去,可以看到初始化的index值传入的是0


简单理解责任链模式4-链接类
  • 具体的处理者(有5个)
public final class RetryAndFollowUpInterceptor implements Interceptor {
  ......
  @Override 
  public Response intercept(Chain chain) {
     ....
     response = ((RealInterceptorChain) chain).proceed(request, streamAllocation,     null, null);
     .....
    }
}
public final class BridgeInterceptor implements Interceptor {
   @Override 
   public Response intercept(Chain chain) throws IOException {
      ......
      Response networkResponse = chain.proceed(requestBuilder.build());
      .......
    }
}
public final class CacheInterceptor implements Interceptor {
   @Override 
   public Response intercept(Chain chain) throws IOException {
      ......
    networkResponse = chain.proceed(networkRequest);
      .......
    }
}
public final class ConnectInterceptor implements Interceptor {
    @Override
  public Response intercept(Chain chain) throws IOException {
    RealInterceptorChain realChain = (RealInterceptorChain) chain;
    ...
    return realChain.proceed(request, streamAllocation, httpCodec, connection);
  }
}
/** This is the last interceptor in the chain. It makes a network call to the server. */
public final class CallServerInterceptor implements Interceptor {
    @Override 
    public Response intercept(Chain chain) throws IOException {
      .....
     //类上有注释,这是链上的最后一个拦截器,所以就没调用proceed()了
    }
}

对比下,下面是简单的一个demo,上面是实际项目中的应用


简单理解责任链模式4-具体的处理者
  • 抽象处理者
public interface Interceptor {
  Response intercept(Chain chain) throws IOException;

  interface Chain {
    Request request();
    //链头的具体处理者
    Response proceed(Request request) throws IOException;

    Connection connection();
  }
}

1)在责任链模式的概念中把抽象处理类都是定义成abstract类,在OKHttp的实际应用中我们看到是定义成interface的
2)demo和实际对比,发现实际中把链头的具体处理者定义成一个接口的,让RealInterceptorChain去实现这个接口

public final class RealInterceptorChain implements Interceptor.Chain {
      @Override
      public Response proceed(Request request) throws IOException {
          return proceed(request, streamAllocation, httpCodec, connection);
      }

      public Response proceed(....) throws IOException {
          // Call the next interceptor in the chain.
          RealInterceptorChain next = new RealInterceptorChain(
          interceptors, streamAllocation, httpCodec, connection, index + 1, request);
          Interceptor interceptor = interceptors.get(index);
          //这里调用抽象接口自己的抽象方法
          Response response = interceptor.intercept(next);
          return response;
       }
    
}
简单理解责任链模式4-抽象处理者
3、OKHttp责任链模式的结构图

(第一次画这个图,折腾了好久,尤其是Interceptor和Chain之间的关系,我用了一个关联,不知道到底对不对,有问题的话,请帮忙指出,好修正,谢谢!)

OKHttp责任链模式.png
3、OKHttp实现原理图

从参考文档中的博主哪儿借用一张原理图,懒得自己去画了


原理图
参考文档

OKHttp中的责任链模式
总结中说到哪些著名的框架用到了责任链模式

相关文章

  • 从OKHttp源码中看责任链模式

    上篇文章简单理解责任链模式只做了Demo,这篇文章就结合OKHttp的框架来具体看看责任链模式,没看过上篇文章的建...

  • okhttp网络框架源码浅析(二)

    okhttp网络框架源码浅析(一) interceptors责任链 不清楚责任链设计模式,可以先了解一下责任链设计...

  • Okhttp3 Interceptor(三)

    前言 OkHttp 中的 Interceptor 是通过责任链模式来设计的, 责任链模式参考: 责任链模式 , 至...

  • 高仿okhttp手写责任链模式

    okhttp使用的设计模式面试的时候经常被问到,其中里面最多的建造者模式和责任链模式其中责任链模式也是okhttp...

  • OkHttp设计模式剖析(三)策略模式

    上一篇 OkHttp设计模式剖析(二)责任链模式 下一篇 OkHttp设计模式剖析(四)享元模式 OKHTTP...

  • OkHttp源码之RetryAndFollowUpInterce

    之前在上一篇文章okhttp源码之责任链模式中有提到过,okhttp的所有功能都是通过拦截器来实现的,就是我们今天...

  • Okhttp之RetryAndFollowUpIntercept

    如果研究过okhttp源码,应该知道okhttp的核心是拦截器,而拦截器所采用的设计模式是责任链设计,即每个拦截器...

  • Okhttp之BridgeInterceptor拦截器解析

    如果研究过okhttp源码,应该知道okhttp的核心是拦截器,而拦截器所采用的设计模式是责任链设计,即每个拦截器...

  • OkHttp源码之责任链模式

    对于okhttp来说,它的拦截器各位肯定是非常熟悉的,正是由于它的存在,okhttp的扩展性极强,对于调用方来说可...

  • 责任链模式与 OkHttp

    什么是责任链模式 OkHttp中责任链模式的实现 一、什么是责任链模式 使多个对象都有机会处理请求,从而避免了请求...

网友评论

      本文标题:从OKHttp源码中看责任链模式

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