Java 责任链模式demo

BaseValidateChain

public abstract class BaseValidateChain {

    // 当前处理节点
    protected BaseValidateChain chain;

    // 设置下一个处理者
    public void setNextChain(BaseValidateChain nextChain) {
        this.chain = nextChain;
    }

    // 处理方法,每一个处理者要实现该方法
    public abstract Response proceed(ValidateContext context, OrderApplyResultVo orderApplyResultVo);

    public static class Builder {
        // 分别记录第一个处理者和下一个处理者,类似于链表结构
        private BaseValidateChain head;
        private BaseValidateChain tail;

        // 添加处理者
        public Builder addChain(BaseValidateChain chain) {
            if (this.head == null) {
                this.head = this.tail = chain;
                return this;
            }
            // 设置下一个处理者
            this.tail.setNextChain(chain);
            this.tail = chain;
            return this;
        }

        public BaseValidateChain build() {
            return this.head;
        }
    }


}

实现类

@Service
@Slf4j
public class AirlineValidateChain extends BaseValidateChain {

    @Resource
    private OrderService orderService;
    @Resource
    private OrderDataServiceFactory orderDataServiceFactory;
    @Resource
    private ProductBasicBiz productBasicBiz;

    @Override
    public Response proceed(ValidateContext context, OrderApplyResultVo orderApplyResultVo) {
        log.info("延航险校验 begin");
        // do something
        if (Objects.nonNull(chain)){
            log.info("延航险校验 end next validate");
            return chain.proceed(context, orderApplyResultVo);
        }

        return ResponseUtil.makeSuccess(orderApplyResultVo);
    }
}
@Service
@Slf4j
public class AnnuityValidateChain extends BaseValidateChain {

    @Resource
    private OrderService orderService;
    @Resource
    private OrderDataServiceFactory orderDataServiceFactory;
    @Resource
    private ProductBasicBiz productBasicBiz;


    @Override
    public Response proceed(ValidateContext context, OrderApplyResultVo orderApplyResultVo) {
        ApplyReqParam applyReqParam = context.getApplyReqParam();
        log.info("校验 begin");
        // do something
        if (Objects.nonNull(chain)){
            log.info("校验 end next validate");
            return chain.proceed(context, orderApplyResultVo);
        }
        return ResponseUtil.makeSuccess(orderApplyResultVo);
    }
}

形成链条

 new BaseValidateChain.Builder()
                .addChain(airlineValidateChain)
                .addChain(annuityValidateChain)
                .build();
        Response voResponse = airlineValidateChain.proceed(context, orderApplyResultVo);

你可能感兴趣的:(java,java,责任链模式,链表)