一、简单模型
责任链设计模式中,输入输出顺序处理。
输入输出模型
这个比较简单,定义一个接口,前一个实现类的输入是后一个的输出,每一个实现类都链条上的处理节点。
public interface Interceptor {
public String intercept(String src);
}
可以定义很多Interceptor实现类处理节点, 当然,也可以不返回结果,每个节点依次处理,也可以定义一个在实现类中引用多个处理节点。
public class InterceptorChain {
List<Interceptor> interceptors;
public InterceptorChain(List<Interceptor> interceptors) {
this.interceptors = interceptors
}
public String intercept(String src) {
//遍历列表处理
//自己处理
}
}
总之,这种方式是将输入信息经过一个链式节点集,处理顺序也可以控制,相对简单。
在网络请求的场景中,数据的输入和输出都要处理。Request数据经过一系列处理,在最后一个节点处理完成后,将其发送出去,Response数据获取,返回给上层用户前也要经过一系列处理,这种比较复杂。类似七层网络协议。
二、复杂模型(基于Okhttp)
下面举例4个拦截器,既可以拦截Request,也可以拦截Response,拦截顺序注意一下。
复杂模型
拦截器一共有四个节点,输入处理顺序,第一个节点优先,输出处理顺序,最后一个节点先处理。
public interface Interceptor {
Response intercept(Chain chain) throws IOException;
interface Chain {
//处理
Response proceed(Request request) throws IOException;
}
}
定义两个接口,Interceptor和Chain,每一个拦截器节点实现的是intercept方法,传入Chain链,从Chain中拿到Request请求处理。
Chain的实现是统一的,看一下Chain的proceed方法。它内部有整条拦截器处理节点和请求实体。
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpCodec, connection, index + 1, request);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
创建新Chain链,找到下一个拦截器,intercept方法,传入新链。
List<Interceptor> interceptors = new ArrayList<>();
interceptors.add(new BridgeInterceptor(client.cookieJar()));
interceptors.add(new CacheInterceptor(client.internalCache()));
interceptors.add(new ConnectInterceptor(client));
...
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
chain.proceed(originalRequest)
多个拦截器节点,他们的intercept方法大致如下过程。
Response intercept(Chain chain) {
//从chain中获取Request,处理
...
//回到chain,找下一个拦截器处理
Response response =chain.proceed(Request request)
//处理response
return response;
}
因此,前面的拦截器先处理Reqest,后面的拦截器先处理Response。
三、总结
数据流需要处理输入和输出时,采用责任链设计模式,链条上的处理节点,互不影响。具体拦截者只负责自己的那一块,拦截处理,每个拦截者实现动态热插拔,输入和输出解耦。
任重而道远