模仿OKhhtp的责任链模式
1)首先两个接口
public interface Interceptors {
int intercept(Chain chain) ;
interface Chain{
int proceed();
}
}
2)接口实现类
//第一个接口实现类 我们模拟到最后一个类才返回真正的数据
public class MyInterceptors implements Interceptors {
@Override
public int intercept(Interceptors.Chain chain) {
//这里可做一些业务 构建
return chain.proceed();
}
public static class MyInterceptorsa implements Interceptors {
@Override
public int intercept(Chain chain) {
return chain.proceed();
}
}
public static class MyInterceptorsb implements Interceptors {
@Override
public int intercept(Chain chain) {
return chain.proceed();
}
}
public static class MyInterceptorsc implements Interceptors {
@Override
public int intercept(Chain chain) {
return chain.proceed();
}
}
public static class MyInterceptorsd implements Interceptors {
@Override
public int intercept(Chain chain) {
return chain.proceed();
}
}
public static class MyInterceptorse implements Interceptors {
@Override
public int intercept(Chain chain) {
return 5;
}
}
}
//这个是核心类
public class RealInterceptorChain implements Interceptors.Chain {
List<Interceptors> interceptors;
final int index;
@Override
public int proceed() {
System.out.println("====index===" + index);
if (index >= interceptors.size()) {
return -10000;
} else {
RealInterceptorChain next = new RealInterceptorChain(interceptors, index + 1);
Interceptors interceptor = interceptors.get(index);
int response = interceptor.intercept(next);
return response;
}
}
public RealInterceptorChain(List<Interceptors> interceptors, int index) {
this.interceptors = interceptors;
this.index = index;
}
}
3)测试
public static void main(String[] args) {
ArrayList<Interceptors> interceptors = new ArrayList<>();
interceptors.add(new MyInterceptors());
interceptors.add(new MyInterceptors.MyInterceptorsa());
interceptors.add(new MyInterceptors.MyInterceptorsb());
interceptors.add(new MyInterceptors.MyInterceptorsc());
interceptors.add(new MyInterceptors.MyInterceptorsd());
interceptors.add(new MyInterceptors.MyInterceptorse());
RealInterceptorChain mRealInterceptorChain = new RealInterceptorChain(interceptors, 0);
System.out.println("====a == b >>>>>" + mRealInterceptorChain.proceed());
}
打印出结果
====index===0
====index===1
====index===2
====index===3
====index===4
====index===5
====a == b >>>>>5
网友评论