1 总览
2 概念
避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。职责链模式是一种对象行为型模式。
3 实现
公共部分,一个系统仅需要一个
3.1 责任链传递的数据,所有对象实现该接口
/*** 真正存储着责任链的数据*/
public interface ProcessModel {}
3.2 责任链上下文,包含请求和返回结果(结果代码中自定义),中断标识等
public class ProcessContext<T extends ProcessModel> {/*** 存储责任链上下文具体请求数据*/private T processModel;/*** 责任链中断的标识*/private Boolean needBreak;/*** 每个链路处理的结果*/XXXResponse response;public T getProcessModel() {return processModel;}public void setProcessModel(T processModel) {this.processModel = processModel;}public Boolean getNeedBreak() {return needBreak;}public void setNeedBreak(Boolean needBreak) {this.needBreak = needBreak;}public XXXResponse getResponse() {return response;}public void setResponse(XXXResponse response) {this.response = response;}
}
3.3 抽象责任链接口
public interface AbstractChainProcessor<T extends ProcessModel> {void processRequest(ProcessContext<T> request);
}
3.4 责任链具体实现(多个,按需实现)
3.5 责任链组装
/*** @author sighting* @version 1.0.0.0* @description: 消息发送处理模版* @date 2022/12/1 4:11 下午*/public class ProcessTemplate {private List<AbstractChainProcessor> processList;public List<AbstractChainProcessor> getProcessList() {return processList;}public void setProcessList(List<AbstractChainProcessor> processList) {this.processList = processList;}}
调用方组装责任链(非公共部分,按需实现),设置链执行顺序,当然也可以每个对象中设置责任链的下游对象,具体实现为,在抽象责任链中增加第二段代码
public ProcessTemplate getAsseblyChain(String exeMode) {ProcessTemplate processTemplate = new ProcessTemplate();MessageSendModeEnum sendMode = MessageSendModeEnum.getByName(exeMode);BizValidation.isTrueBCheck(MessageResultCode.SEND_MODE_NOT_SUPPORT, sendMode != null,null);if (MessageSendModeEnum.SYNC.getCode() == sendMode.getCode()) {processTemplate.setProcessList(Arrays.asList(xxxx,xxxx));} else {processTemplate.setProcessList(Arrays.asList(xxx,ssss,needed));}return processTemplate;}
//维持对下家的引用
protected Handler successor;
public void setSuccessor(Handler successor) {this.successor=successor;
}
3.6 使用实例:责任链具体使用
//责任链入参ProcessContext<MessageSendReqBO> processContext = new ProcessContext<>();processContext.setProcessModel(reqBO);processContext.setNeedBreak(false);processContext.setResponse(new SimbaResponse());try {//责任链处理for (AbstractChainProcessor businessProcess : 上个方法.getAsseblyChain(reqBO.getExecMode()).getProcessList()) {businessProcess.processRequest(processContext);if (processContext.getNeedBreak()) {break;}}} catch (Exception e) {log.error("chains exe failed",e)}