### 前言
回顾:
[Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f)
[Okhttp3源码解析(1)-OkHttpClient分析](https://www.jianshu.com/p/bf1d01b79ce7)
[Okhttp3源码解析(2)-Request分析](https://www.jianshu.com/p/5a85345c8ea7)
[Okhttp3源码解析(3)-Call分析(整体流程)](https://www.jianshu.com/p/4ed79472797a)

上节我们讲了okhttp的整体的流程,里面的核心方法之一是`getResponseWithInterceptorChain()` ,这个方法应该知道吧?通过拦截器层层处理返回Response;这个方法中其实应用了责任链设计模式。今天主要讲一下它是如何应用的!

### 责任链设计模式
###### 责任链模式的定义

在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求,这使得系统可以在不影响客户端的情况下动态地重新组织和分配责任。

模型:

![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190827082427829-283762395.png)

1.优点
耦合度降低,请求和处理是分开的
2.缺点
责任链太长或者每条链判断处理的时间太长会影响性能。特别是递归循环的时候
不一定被处理,每个职责类的职责很明确,这就需要对写默认的处理了
**责任链模式重要的两点:分离职责,动态组合**
对责任链设计模式不明白的可以去网上那个找找实例看看, 这里就不举例子了。

### 源码中的责任链
话不多说,直接上`getResponseWithInterceptorChain()` 源码
```
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List interceptors = new ArrayList();
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, this, eventListener, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());

return chain.proceed(originalRequest);
}
```
方法中大部分上节已经说了,就是 `List`添加自定义、cookie等等的拦截器,今天我们主要看看后半部分:
```
Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0,
originalRequest, this, eventListener, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());

return chain.proceed(originalRequest);
```
首先初始化了 `RealInterceptorChain`,`RealInterceptorChain`是`Interceptor.Chain`的实现类
![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190827082428677-935973782.png)

先看一下`Interceptor.Chain`:
```
public interface Interceptor {
Response intercept(Chain chain) throws IOException;

interface Chain {
Request request();

Response proceed(Request request) throws IOException;

//部分代码省略....
}
}

```

生成了RealInterceptorChain的实例,调用了`proceed()`,返回了最后的Response
我们看下 `RealInterceptorChain`类中的`proceed()`:
```
@Override public Response proceed(Request request) throws IOException {
return proceed(request, streamAllocation, httpCodec, connection);
}

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
if (index >= interceptors.size()) throw new AssertionError();

calls++;

// If we already have a stream, confirm that the incoming request will use it.
if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
+ " must retain the same host and port");
}

// If we already have a stream, confirm that this is the only call to chain.proceed().
if (this.httpCodec != null && calls > 1) {
throw new IllegalStateException("network interceptor " + interceptors.get(index - 1)
+ " must call proceed() exactly once");
}

// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec,
connection, index + 1, request, call, eventListener, connectTimeout, readTimeout,
writeTimeout);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);

// Confirm that the next interceptor made its required call to chain.proceed().
if (httpCodec != null && index + 1

Okhttp3源码解析(4)-拦截器与设计模式的更多相关文章

  1. Okhttp3源码解析(5)-拦截器RetryAndFollowUpInterceptor

    ### 前言 回顾: [Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f) [Okhttp3源码解析(1)-OkHttpClient分析](htt ...

  2. 源码解析Grpc拦截器(C#版本)

    前言 其实Grpc拦截器是我以前研究过,但是我看网上相关C#版本的源码解析相对少一点,所以笔者借这篇文章给大家分享下Grpc拦截器的实现,废话不多说,直接开讲(Grpc的源码看着很方便,包自动都能还原 ...

  3. axios源码解析 - 请求拦截器

    axios请求拦截器,也就是在请求发送之前执行自定义的函数. axios源码版本 - ^0.27.2 (源码是精简版) 平时在业务中会这样去写请求拦截器,代码如下: // 创建一个新的实例 var s ...

  4. axios 源码解析(下) 拦截器的详解

    axios的除了初始化配置外,其它有用的应该就是拦截器了,拦截器分为请求拦截器和响应拦截器两种: 请求拦截器    ;在请求发送前进行一些操作,例如在每个请求体里加上token,统一做了处理如果以后要 ...

  5. Okhttp3源码解析(3)-Call分析(整体流程)

    ### 前言 前面我们讲了 [Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f) [Okhttp3源码解析(1)-OkHttpClient分析]( ...

  6. springMVC源码分析之拦截器

    一个东西用久了,自然就会从仅使用的层面上升到探究其原理的层面,在javaweb中springmvc更是如此,越是优秀的框架,其底层实现代码更是复杂,而在我看来,一个优秀程序猿就相当于一名武林高手,不断 ...

  7. springMVC源码分析--HandlerInterceptor拦截器调用过程(二)

    在上一篇博客springMVC源码分析--HandlerInterceptor拦截器(一)中我们介绍了HandlerInterceptor拦截器相关的内容,了解到了HandlerInterceptor ...

  8. Okhttp3源码解析(2)-Request分析

    ### 前言 前面我们讲了 [Okhttp的基本用法](https://www.jianshu.com/p/8e404d9c160f) [Okhttp3源码解析(1)-OkHttpClient分析]( ...

  9. SpringMVC源码阅读:拦截器

    1.前言 SpringMVC是目前J2EE平台的主流Web框架,不熟悉的园友可以看SpringMVC源码阅读入门,它交代了SpringMVC的基础知识和源码阅读的技巧 本文将通过源码(基于Spring ...

随机推荐

  1. Catalan公式

    f(n)=f(1)*f(n-1)+f(2)*f(n-2)+f(3)*f(n-3)+......+f(n-1)*f(1) 例用:一个长度为n的无重复序列入栈的所有出栈方式

  2. CIDR的介绍

    CIDR的介绍: CIDR(Classless Inter-Domain Routing,无类域间路由选择)它消除了传统的A类.B类和C类地址以及划分子网的概念,因而可以更加有效地分配IPv4的地址空 ...

  3. php的中文字符

    在使用substr截取字符窜的时候出现乱码的问题 一直任认为字符串是2个字节,直到多次才尝试才总算知道问题所在 php的utf-8字符是每个字符3个字节 而gbk字符是每个字节2个字符 单个字母和符号 ...

  4. Hadoop自学系列集(四) ---- Hadoop集群

    久等了,近期公司比较忙,学习的时间都没有啊,到今日才有时间呢!!!好了,下面就跟着笔者开始配置Hadoop集群吧. hosts文件和SSH免密码登录配置好了之后,现在进入Hadoop安装目录,修改一些 ...

  5. Java中Timer和TimerTask来实现计时器循环触发

    package xian; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.Fi ...

  6. H3C模拟器实验之网络地址转换

    网络拓扑图 NOTE:各个设备的基本配置在拓扑图上已经标明(需要注意的是RTB的出接口也需要配置IP,但是使用ping -a 10.1.1.1 202.117.144.1 ping不通,这点不是很理解 ...

  7. (13)ASP.NET Core 中的选项模式(Options)

    1.前言 选项(Options)模式是对配置(Configuration)的功能的延伸.在12章(ASP.NET Core中的配置二)Configuration中有介绍过该功能(绑定到实体类.绑定至对 ...

  8. 转载:MyBatis mapper.xml中使用静态常量或者静态方法

    转自:https://my.oschina.net/wtslh/blog/682704 今天偶然之间刷到了这样一篇博客,有点意外 mybatis 还可以这样使用ONGL常量的方式,该方式针对 xml的 ...

  9. .NET----错误和异常处理机制

    前言 错误的出现并不总是编写程序的人的原因,有时应用程序会因为应用程序的最终用户引发的动作或运行代码的环境发生错误.无论如何,我们都应预测应用程序中出现的错误,并相应的进行编码. .Net改进了处理错 ...

  10. ext container的使用的场景

    container 是 panel 简化,他称之为容器,而panel则是面板. 如果不需要类似Ext.panel.Panel,Ext.window.Window和Ext.tab.Panel 等功能,则 ...