拦截器接口
public interface Interceptor {
String interceptor(Chain chain);
interface Chain{
String request();
String proceed(String request);
}
}
实现3个拦截器
public class BridgeInterceptor implements Interceptor{
@Override
public String interceptor(Chain chain) {
System.out.println("执行 BridgeInterceptor 拦截器之前代码");
String proceed = chain.proceed(chain.request());
System.out.println("执行 BridgeInterceptor 拦截器之后代码 得到最终数据:"+proceed);
return proceed;
}
}
public class RetryAndFollowInterceptor implements Interceptor {
@Override
public String interceptor(Chain chain) {
System.out.println("执行 RetryAndFollowInterceptor 拦截器之前代码");
String proceed = chain.proceed(chain.request());
System.out.println("执行 RetryAndFollowInterceptor 拦截器之后代码 得到最终数据:" + proceed);
return proceed;
}
}
public class CacheInterceptor implements Interceptor {
@Override
public String interceptor(Chain chain) {
System.out.println("执行 CacheInterceptor 最后一个拦截器 返回最终数据");
return "success";
}
}
实现chain接口
public class RealInterceptorChain implements Interceptor.Chain {
private List<Interceptor> interceptors;
private int index;
private String request;
public RealInterceptorChain(List<Interceptor> interceptors, int index, String request) {
this.interceptors = interceptors;
this.index = index;
this.request = request;
}
@Override
public String request() {
return request;
}
@Override
public String proceed(String request) {
if (index >= interceptors.size()) return null;
RealInterceptorChain next = new RealInterceptorChain(interceptors,index+1,request);
Interceptor interceptor = interceptors.get(index);
return interceptor.interceptor(next);
}
}
下面是测试代码
public class Test {
public static void main(String args[]) {
List<Interceptor> interceptors = new ArrayList<>();
interceptors.add(new BridgeInterceptor());
interceptors.add(new RetryAndFollowInterceptor());
interceptors.add(new CacheInterceptor());
RealInterceptorChain request = new RealInterceptorChain(interceptors, 0, "request");
request.proceed("request");
}
}
输出结果是:
执行 BridgeInterceptor 拦截器之前代码
执行 RetryAndFollowInterceptor 拦截器之前代码
执行 CacheInterceptor 最后一个拦截器 返回最终数据
执行 RetryAndFollowInterceptor 拦截器之后代码 得到最终数据:success
执行 BridgeInterceptor 拦截器之后代码 得到最终数据:success
重点:
每个拦截器的
chain.proceed()方法前是对请求的处理,之后是对返回的处理。这个是责任链模式的关键。