责任链模式

责任链模式

一条链路,按照顺序执行,中间出现问题,可以退出return
常用与参数校验,接入层的相关处理逻辑
固定套路

1.定义数据处理模型基类

public interface ProcessModel {
}

2.抽象Context里包含数据处理模型,处理器之间传递context

使用到了泛型上限的特性,限制只能实现了ProcessModel的数据对象进context进行处理

@Data
@Builder
public class ProcessContext<T extends ProcessModel> {
    T processModel;
    Boolean needBreak; // 是否需要跳出的标志位
    BasicResultVO response; // 返回结构
}

3.定义处理器接口

public interface BusinessProcessor<T extends ProcessModel> {
    void process(ProcessContext<T> context);
}

4.定义一个数据模型实现ProcessModel

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
@Accessors(chain = true)
public class NotificationModel implements ProcessModel {
    public Map<NotifyMethod,AlarmNotificationDto> alarmNotificationMap;
    public String ruleKey;
    public String ruleGroupKey;
    public long processTime;
    public long timestamp;
    public AlarmLevel level;
    public String metric;
    public String endpoint;
    public String appEnName;
    public String labels;
    public AlarmNotificationMqData originalMqData;
    public ResourceType resourceType;
    public List<NotifyMethod> notifyMethods;
}

5.定义处理器的实现类,通过泛型传递过来是NotificationModel模型

@Component
@Order(10)
public class PreCheckProcessor implements BusinessProcessor<NotificationModel>{

    @Resource
    AlarmRuleNewMapper alarmRuleNewMapper;

    @Resource
    AlarmRuleTemplateNewMapper alarmRuleTemplateNewMapper;

    @Resource
    RelationAlarmRuleNotifyMethodMapper relationAlarmRuleNotifyMethodMapper;

    @Override
    public void process(ProcessContext<NotificationModel> context) {
		// condition
		if (条件){
			context.setNeedBreak(true);
			context.setResponse(BasicResultVO.fail("告警规则模板通知开关状态:关闭"))
			return
		}
    }
}
接着写后面的处理类,里面Order注解指定不同的数字,数字越大,越后执行

6.生成责任链路,按照链路执行

@Component
public class ProcessorChain {

    @Resource
    List<BusinessProcessor> processorList;


    public ProcessContext process(ProcessContext context){
        for (BusinessProcessor processor : processorList) {
            processor.process(context);
            if (context.needBreak){
                break;
            }
        }
        return context;
    }
}

7.测试

创建NotificationModel,传递进ProcessContext里,用责任链执行

// 创建ProcessModel
NotificationModel notificationModel = NotificationModel.builder().originalMqData(mqObj).build();
// 生成运行时context
ProcessContext<ProcessModel> processContext = ProcessContext.builder()
	.processModel(notificationModel).needBreak(false)
	.response(BasicResultVO.success())
	.build();
processorChain.process(processContext);

8.流程审批可以用这个模式

posted @ 2022-12-30 11:06  SpecialSpeculator  阅读(55)  评论(0编辑  收藏  举报