大学上 UML 课程的时候总觉得设计模式遥不可及、无法理解,印象最深的是 UML 课程期末考试的最后一题是责任链模式相关的内容,我没有做出来。毕业后,也曾抱着《设计模式·可复用面向对象软件的基础》从头开始看,总感觉一头雾水,少点什么。
如今看来,当时还是见得太少,经验不足。

书中关于的责任链模式的主要例子是多视窗对用户事件的处理,Android 系统中 View 树对触摸事件的分发处理流程也用到了责任链模式。
该模式的核心想法是:
给多个对象处理一个请求的机会,从而解耦发送者和接受者,该请求沿着对象链传递直到其中一个对象处理它。
对于 Http 客户端请求,两个主要工作是处理缓存和网络请求,这两部分都有机会处理 Http 请求,而且存在一种场景是离线状态且缓存可用,这时的请求便只由缓存部分处理。采用责任链模式可以很优雅地将缓存和网络职责分离,而且 Cache 部分总是先于 Socket 处理请求。
源码
官网给的例子如下:
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
我看文章的时候总是很讨厌大段大段的代码,因为我自己会把源码打开,边看边理解。但为了文章的完整性,不得不放一点源码。
我们只看同步执行的过程:
@Override public Response execute() throws IOException {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
eventListener.callStart(this);
try {
client.dispatcher().executed(this);
Response result = getResponseWithInterceptorChain();
if (result == null) throw new IOException("Canceled");
return result;
} catch (IOException e) {
eventListener.callFailed(this, e);
throw e;
} finally {
client.dispatcher().finished(this);
}
}
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> 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);
}
在这里我们可以清楚地看到整条链式由 Interceptor 数组构成,依次是开发者自定义的普通 Interceptor、处理 Cookie的 Interceptor、处理 Cache 的 Interceptor、创建连接的 Interceptor、开发者自定义的网络 Interceptor(可以用于添加下载进度功能)、真正发起网络请求的 Interceptor。
处理请求的传递的实现部分在RealInterceptorChain类里:
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
// 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);
return response;
}
每个 Interceptor 里的 intercept 函数会拦截请求,做自己的工作,然后调用 Chain 里的 proceed 函数,将 index 增 1,传递 Request 给下一个拦截器处理。
CallServerInterceptor 是个例外,由于是整条处理链的最后一个拦截器,这里直接处理网络请求,返回 Response,不再继续传递。
值得一提的是 CacheInterceptor 类对 Http 协议的缓存设计做了完整的实现,很适合拿来学习Http协议的缓存处理,具体的细节便不在这里细说了。
小结
OkHttp 源码读起来确实很优雅,很顺畅,但是如果是我们面对Http客户端的实现需求,是否能想到这么优雅的设计方案。和理解原理比起来,仅仅会使用库还远远不够;和设计实现比起来,仅仅理解原理也同样远远不够。