淺談JAVA工作流的優(yōu)雅實現(xiàn)方式
今天查找線上問題,看到一個讓我腦洞大開的工作流實現(xiàn)方式。以前用過責(zé)任鏈模式,也用過模板模式實現(xiàn)類工作流的方式,但是對比這個工具,遜色不少,不賣關(guān)子了,就是Apache Commons Chain,它是Command模式與責(zé)任鏈模式的綜合體。
1、Apache Commons Chain 中的角色有:chain、context、command。

2、在我們訂單系統(tǒng)有這樣的業(yè)務(wù),就是退票的時候,會根據(jù)核損后的訂單價格,給客人退錢,但是訂單的金額,由幾部分組成
有現(xiàn)金、商旅卡、有優(yōu)惠券。所以根據(jù)需求,我們需要一個工作流來走下退款流程,我們的流程流轉(zhuǎn)的步驟是這樣的:
先退商旅卡-----如果還有余額退現(xiàn)金-----------還有余額再退優(yōu)惠券,分析一下這樣的需求,剛好可以用這個工具,直接上代碼了
先引入包
<dependency>
<groupId>commons-chain</groupId>
<artifactId>commons-chain</artifactId>
<version>1.2</version>
</dependency>
編寫command
/**
* 退商旅卡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;
}
}
/**
* 退現(xiàn)金
* 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:{}退款開始,第二步:退現(xiàn)金,金額:{}",refundContext.getOrderId(),"5");
return false;
}
}
/**
* 退優(yōu)惠券
* 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:{} 退款開始,第二步:退優(yōu)惠券,金額:{}",refundContext.getOrderId(),"20");
return false;
}
}
/**
* Created by 一代天驕 on 2018/7/1.
*/
@Data
public class RefundContext extends ContextBase {
/**
* 訂單號
*/
private Integer orderId;
}
/**
*
* 退票的工作流實現(xiàn)
* Created by 一代天驕 on 2018/7/1.
*/
public class RefundTicketChain extends ChainBase {
public void init() {
//退商旅卡
this.addCommand(new RefundBusinessCardCommand());
//退現(xiàn)金
this.addCommand(new RefundCashCommand());
//退優(yōu)惠券
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);
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
springboot實現(xiàn)rabbitmq的隊列初始化和綁定
這篇文章主要介紹了springboot實現(xiàn)rabbitmq的隊列初始化和綁定,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-10-10
基于Java開發(fā)實現(xiàn)ATM系統(tǒng)
這篇文章主要為大家詳細介紹了基于Java開發(fā)實現(xiàn)ATM系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-08-08

