好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

浅谈JAVA工作流的优雅实现方式

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

1、apache commons chain 中的角色有:chain、context、command。

2、在我们订单系统有这样的业务,就是退票的时候,会根据核损后的订单价格,给客人退钱,但是订单的金额,由几部分组成

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

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

先引入包

?

1

2

3

4

5

<dependency>

      <groupid>commons-chain</groupid>

      <artifactid>commons-chain</artifactid>

      <version> 1.2 </version>

    </dependency>

编写command

?

1

2

3

4

5

6

7

8

9

10

11

12

/**

  * 退商旅卡cash

  * created by 一代天骄 on 2018/7/1.

  */

@slf4j

public class refundbusinesscardcommand implements command{

   public boolean execute(context context) throws exception {

     refundcontext refundcontext = (refundcontext) context;

     log.info( "orderid:{} 退款开始,第一步:退商旅卡,金额:{}" ,refundcontext.getorderid(), "10" );

     return false ;

   }

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

/**

  * 退现金

  * created by 一代天骄 on 2018/7/1.

  */

@slf4j

public class refundcashcommand implements command {

 

   public boolean execute(context context) throws exception {

     refundcontext refundcontext = (refundcontext) context;

     log.info( "orderid:{}退款开始,第二步:退现金,金额:{}" ,refundcontext.getorderid(), "5" );

     return false ;

   }

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

/**

  * 退优惠券

  * created by 一代天骄 on 2018/7/1.

  */

@slf4j

public class refundpromotioncommand implements command{

 

 

   public boolean execute(context context) throws exception {

     refundcontext refundcontext = (refundcontext) context;

     log.info( "orderid:{} 退款开始,第二步:退优惠券,金额:{}" ,refundcontext.getorderid(), "20" );

     return false ;

   }

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

/**

  * created by 一代天骄 on 2018/7/1.

  */

@data

public class refundcontext extends contextbase {

 

   /**

    * 订单号

    */

   private integer orderid;

 

 

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

/**

  *

  * 退票的工作流实现

  * created by 一代天骄 on 2018/7/1.

  */

public class refundticketchain extends chainbase {

 

   public void init() {

     //退商旅卡

     this .addcommand( new refundbusinesscardcommand());

     //退现金

     this .addcommand( new refundcashcommand());

     //退优惠券

     this .addcommand( new refundpromotioncommand());

   }

 

 

   public static void main(string[] args) throws exception {

     refundticketchain refundticketchain = new refundticketchain();

     refundticketchain.init();

     refundcontext context = new refundcontext();

     context.setorderid( 1621940242 );

     refundticketchain.execute(context);

   }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

原文链接:https://blog.csdn.net/vacblog/article/details/80875788

查看更多关于浅谈JAVA工作流的优雅实现方式的详细内容...

  阅读:13次