责任链模式

写一个项目,功能模块需要拆分

其实 责任链,他的每一个 链节,其实就是不同的功能,只不过比之于正常的写项目的 功能拆分,他的功能是有依赖性的。

比如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即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值