适用场景
审批任务,流程任务(代码执行具有一定的固定性,不同业务之前区别只在于部分业务可不执行的情况),降低流程间的耦合度、实现业务场景低耦合、增加开发效率
实际场景
贷款业务场景: 数据必输项校验、保存贷款信息、请求额度系统查询实时额度、请求风险系统校验、发送短信通知(微信通知). 大部分渠道方的流程大致如此.细微差异在于有些渠道可能不需要发送短信、或者需要发送微信通知,与总流程不同.这种情况就可以使用责任链模式
代码开发:
- 首先抽象出一个链条组装对象(负责流程的组装,前置节点与当前节点维护)
package com.ts;
/**
* @author haizhuangbu
* @date 2024/1/20 13:48
* @mark LcApplyLimitChain
*/
public abstract class LcApplyLimitChain {
private LcApplyLimitChain chain;
/**
* @param chain 下一节点
*/
public void nextChain(LcApplyLimitChain chain) {
this.chain = chain;
}
protected abstract void run();
public void doRun() {
this.run();
if (chain != null) {
chain.doRun();
}
}
public static class Builder {
// 头节点
private LcApplyLimitChain headChain;
// 下一节点
private LcApplyLimitChain tailChain;
public Builder next(LcApplyLimitChain chain) {
// 第一个环节,头尾只有一个
if (headChain == null && tailChain == null) {
this.headChain = tailChain = chain;
return this;
}
// 下一环节,节点
this.tailChain.nextChain(chain);
this.tailChain = chain;
return this;
}
public LcApplyLimitChain build() {
return headChain;
}
}
}
- 具体任务对象(数据校验、贷款信息保存、额度系统
-
- 例如: 数据校验对象
-
package com.ts.impl; import com.ts.LcApplyLimitChain; /** * @author haizhuangbu * @date 2024/1/20 13:57 * @mark DataCheckChain */ public class DataCheckChain extends LcApplyLimitChain { @Override public void run() { System.out.println(" ========= 数据校验节点执行完成 ============"); } }
- 责任链组装、调用
package com.ts;
import com.ts.impl.CreditLimitChain;
import com.ts.impl.DataCheckChain;
import com.ts.impl.SaveLcApplyLimitChain;
import com.ts.impl.SendMsgChain;
/**
* @author haizhuangbu
* @date 2024/1/20 13:59
* @mark LcApplyLimitChainTs
*/
public class LcApplyLimitChainTs {
public static void main(String[] args) {
LcApplyLimitChain chain = new LcApplyLimitChain.Builder()
.next(new DataCheckChain())
.next(new SaveLcApplyLimitChain())
.next(new CreditLimitChain())
.next(new SendMsgChain()).build();
chain.doRun();
}
}
调用效果,需要添加或者取消某一链条、直接改动next就行、不需要跑重复代码
高级用法:
利用范性可以增强责任(任务)链模式,让我们重新改造一下,适应更多场景
核心代码:
具体实现类
实现效果
注: 我在实际开发中,除了next拼接下一节点外,还可以添加一些额外方法filter 添加方法执行过滤,类似于lombda中的filter用法. 主要目的是为了低耦合,功能越复杂,耦合性越高.需要注意取舍