今天查找线上问题,看到一个让我脑洞大开的工作流实现方式。以前用过责任链模式,也用过模板模式实现类工作流的方式,但是对比这个工具,逊色不少,不卖关子了,就是Apache Commons Chain,它是Command模式与责任链模式的综合体。

    1.Apache Commons Chain 中的角色有:chain、context、command。
    工作流引擎Apache Commons Chain - 图1
    2.在我们订单系统有这样的业务,就是退票的时候,会根据核损后的订单价格,给客人退钱,但是订单的金额,由几部分组成

    有现金、商旅卡、有优惠券。所以根据需求,我们需要一个工作流来走下退款流程,我们的流程流转的步骤是这样的:

    先退商旅卡——-如果还有余额退现金—————-还有余额再退优惠券,分析一下这样的需求,刚好可以用这个工具,直接上代码了

    先引入包

    1. <dependency>
    2. <groupId>commons-chain</groupId>
    3. <artifactId>commons-chain</artifactId>
    4. <version>1.2</version>
    5. </dependency>

    编写command

    1. /**
    2. • 退商旅卡Cash
    3. • Created by 一代天骄 on 2018/7/1.
    4. */
    5. @Slf4j
    6. public class RefundBusinessCardCommand implements Command{
    7. public boolean execute(Context context) throws Exception {
    8. RefundContext refundContext = (RefundContext) context;
    9. log.info("orderId:{} 退款开始,第一步:退商旅卡,金额:{}",refundContext.getOrderId(),"10");
    10. return false;
    11. }
    12. }
    1. /**
    2. • 退现金
    3. • Created by 一代天骄 on 2018/7/1.
    4. */
    5. @Slf4j
    6. public class RefundCashCommand implements Command {
    7. public boolean execute(Context context) throws Exception {
    8. RefundContext refundContext = (RefundContext) context;
    9. log.info("orderId:{}退款开始,第二步:退现金,金额:{}",refundContext.getOrderId(),"5");
    10. return false;
    11. }
    12. }
    1. /**
    2. 退优惠券
    3. Created by 一代天骄 on 2018/7/1.
    4. */
    5. @Slf4j
    6. public class RefundPromotionCommand implements Command{
    7. public boolean execute(Context context) throws Exception {
    8. RefundContext refundContext = (RefundContext) context;
    9. log.info("orderId:{} 退款开始,第二步:退优惠券,金额:{}",refundContext.getOrderId(),"20");
    10. return false;
    11. }
    12. }
    1. /**
    2. • Created by 一代天骄 on 2018/7/1.
    3. */
    4. @Data
    5. public class RefundContext extends ContextBase {
    6. /**
    7. • 订单号
    8. */
    9. private Integer orderId;
    10. }
    1. /**
    2. *
    3. • 退票的工作流实现
    4. • Created by 一代天骄 on 2018/7/1.
    5. */
    6. public class RefundTicketChain extends ChainBase {
    7. public void init() {
    8. //退商旅卡
    9. this.addCommand(new RefundBusinessCardCommand());
    10. //退现金
    11. this.addCommand(new RefundCashCommand());
    12. //退优惠券
    13. this.addCommand(new RefundPromotionCommand());
    14. }
    15. public static void main(String[] args) throws Exception {
    16. RefundTicketChain refundTicketChain = new RefundTicketChain();
    17. refundTicketChain.init();
    18. RefundContext context = new RefundContext();
    19. context.setOrderId(1621940242);
    20. refundTicketChain.execute(context);
    21. }
    22. }