写一个项目,功能模块需要拆分
其实 责任链,他的每一个 链节,其实就是不同的功能,只不过比之于正常的写项目的 功能拆分,他的功能是有依赖性的。
比如okhttp
Response getResponseWithInterceptorChain() throws IOException { List<Interceptor> interceptors = new ArrayList(); interceptors.addAll(this.client.interceptors()); interceptors.add(this.retryAndFollowUpInterceptor); interceptors.add(new BridgeInterceptor(this.client.cookieJar())); interceptors.add(new CacheInterceptor(this.client.internalCache())); interceptors.add(new ConnectInterceptor(this.client)); if (!this.forWebSocket) { interceptors.addAll(this.client.networkInterceptors()); } interceptors.add(new CallServerInterceptor(this.forWebSocket)); Chain chain = new RealInterceptorChain(interceptors, (StreamAllocation)null, (HttpCodec)null, (Connection)null, 0, this.originalRequest); return chain.proceed(this.originalRequest); }
进行了一层层的封装,各个拦截器的顺序有些是需要像这样有序的,功能之间是依赖的。
请抓住核心:
责任链=功能 拆分+功能依赖
然后看看okhttp里的责任链的代码是怎么实现的,各个链节之间是怎么联系起来的?
public Response intercept(Chain chain) throws IOException { response = ((RealInterceptorChain)chain).proceed(request, this.streamAllocation, (HttpCodec)null, (Connection)null); }
然后RealInterceptorChain
public class RealInterceptorChain{
private int count;
private List<Intercept> interceptList;
}
从 第一段代码中可以 知道是采用递归(责任链的核心就是递归啊,下去与上来)。然后OkHttp会有一个List,还有一个 计数,代表 当前递归到那一层了。然后向递归下一层的时候,计数+1即可。