责任链模式
可以去看看okhttp源码.
1.来个责任接口,里面有chain接口,用chain来保持链接.
public interface Intecepter {
void intercept(Chain chain) ;
public interface Chain {
void proceed() ;
}
}
2.来个jeck的责任
public class JeckIntecepter implements Intecepter {
@Override
public void intercept(Chain chain) {
//运行当前的intecepter的事情, 再运行下一个chain
dosomething();
chain.proceed();
}
private void dosomething() {
}
}
3.来个li的责任
public class LiIntercepeter implements Intecepter {
@Override
public void intercept(Chain chain) {
dosomething();
chain.proceed();
}
}
4.来个tom的责任
public class TomIntecepter implements Intecepter {
@Override
public void intercept(Chain chain) {
dosomething();
chain.proceed();
}
}
5.来个责任链接口的实现类,里面主要是接收所有责任集合,责任集合运行的index,另外是proceed方法中,去运行下一个责任
public class RealInterceptorChain implements Intecepter.Chain {
private ArrayList<Intecepter> arrayLists;
private int index;
public RealInterceptorChain(ArrayList<Intecepter> arrayList,int index) {
arrayLists = arrayList;
this.index = index;
}
@Override
public void proceed(){
if (index>=arrayLists.size()){
return;
}
Intecepter.Chain chain = new RealInterceptorChain(arrayLists,index+1);
Intecepter intecepter = arrayLists.get(index);
intecepter.intercept(chain);
}
}
6.测试
public class Test {
public void test() {
ArrayList<Intecepter> intecepters = new ArrayList<>();
intecepters.add(new JeckIntecepter());
intecepters.add(new TomIntecepter());
intecepters.add(new LiIntercepeter());
Intecepter.Chain chain = new RealInterceptorChain(intecepters, 0);
chain.proceed(); //创建下一个intecepterchain, 调用当前的intecepter。
}
}