使用责任链模式解决异步嵌套问题

  1. Chain: 用于表示一个链条对象
    (1)定义一个数组,用于保存这条链所有的interceptor;
    (2)定义一个param,用于保存该链式调用所需的参数;
    (3)包含一个proceed()方法,从第一个interceptor开始,循环调用interceptor的intercept()方法;
    (4)定义一个proceedNext(Interceptor interceptor),接收一个interceptor,表示从传入位置的下一个interceptor继续执行intercept()方法;
  2. Interceptor:用于执行具体逻辑
    (1)包含一个intercept(Chain chain)方法,接收当前chain对象,返回一个Boolean值;
    (2)当执行同步任务时,让interceptor返回false,执行完当前interceptor会立即执行下一个interceptor。
    (3)当执行异步任务时,让intercept()返回true,会结束当前链条的调用,如果异步结果返回后还需要继续执行,则调用chain的proceedNext(Interceptor interceptor)方,会继续执行下一个interceptor。
  3. Param:用于保存该链式调用所需的参数,供所有interceptor使用。
  4. 关键代码:
public class Chain {
    private List<Interceptor> interceptors = new ArrayList<>();
    private Param param;

    public void proceed() {
        for (Interceptor interceptor : interceptors) {
            if (interceptor.intercept(this)) {
                break;
            }
        }
    }

    public void proceedNext(Interceptor interceptor) {
        int index = interceptors.indexOf(interceptor);
        if (index != -1) {
            for (int i = ++index; i < interceptors.size(); ++i) {
                interceptor = interceptors.get(i);
                if (interceptor.intercept(this)) {
                    break;
                }
            }
        }
    }

	... ...

}
  1. UML图
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值