23种设计模式----责任链模式

责任链模式

可以去看看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。
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值