设为首页 加入收藏

TOP

Okhttp3源码解析(4)-拦截器与设计模式(二)
2019-09-03 03:44:55 】 浏览:81
Tags:Okhttp3 源码 解析 拦截 设计模式
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 < interceptors.size() && next.calls != 1) { throw new IllegalStateException("network interceptor " + interceptor + " must call proceed() exactly once"); } // Confirm that the intercepted response isn't null. if (response == null) { throw new NullPointerException("interceptor " + interceptor + " returned null"); } if (response.body() == null) { throw new IllegalStateException( "interceptor " + interceptor + " returned a response with no body"); } return response; } ``` 经过一系列的判断,看下`proceed()`的核心 ``` // 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); ``` 如果对责任链模式有认识的朋友看到上面代码,应该直接就能看出来了,**并能分析出:** - 如果是责任链模式, 那个`intercept()`一定是关键, `Interceptor`是接口,interceptors集合中的拦截器类肯定都实现了 `Interceptor`以及 `interceptor.intercept()` - 每个拦截器 `intercept() `方法中的chain,都在上一个 `chain`实例的 `chain.proceed() `中被初始化,并传递了拦截器List与 `index `,直接最后一个 `chain实例 `执行即停止。 ![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190827082428850-1579043948.png) ### 总结: 每个`chain`的`interceptors`与`index`都是由上一个`chain`初始化传递过来的,在`chain.proceed()`中获取对应的`interceptor实例` 并初始化下一个`chain`,直到最后一个`chain`被执行。 这样就清晰了吧?责任链模式的重点在“链上”,由一条链去处理相似的请求,在链中决定谁来处理这个请求,并返回相应的结果。 ![](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190827082429260-1507882191.png) 这节就说到这,希望对大家有所帮助..... 大家可以关注我的微信公众号:「秦子帅」一个有质量、有态度的公众号! ![公众号](https://img2018.cnblogs.com/blog/1312938/201908/1312938-20190827082429414-2044533379.jpg)
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Android四大组件之BroadcastRecei.. 下一篇Flutter学习笔记(24)--SingleCh..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目