责任链设计模式

一、核心接口定义

MyAbstractChainHandler<T> 接口继承自 Ordered 接口,用于实现链式处理逻辑。

java 复制代码
import org.springframework.core.Ordered;

public interface MyAbstractChainHandler<T> extends Ordered {
    void handle(T requestParam);
    String getChainName();
}

handle 方法处理请求参数,getChainName 方法为处理器分组提供依据。

二、处理上下文实现

MyChainContext<T> 类实现 ApplicationContextAware 接口,管理链式处理过程。

java 复制代码
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class MyChainContext<T> implements ApplicationContextAware {
    private final Map<String, List<MyAbstractChainHandler>> chainContext = new ConcurrentHashMap<>();

    public void handler(String chainName, T requestParam) {
        List<MyAbstractChainHandler> chainHandlers = chainContext.get(chainName);
        if (chainHandlers != null) {
            chainHandlers.forEach(handler -> handler.handle(requestParam));
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, MyAbstractChainHandler> handerBeans = applicationContext.getBeansOfType(MyAbstractChainHandler.class);
        handerBeans.forEach((beanName, bean) -> {
            chainContext.computeIfAbsent(bean.getChainName(), k -> new ArrayList<>()).add(bean);
        });
        chainContext.forEach((chainName, handlers) -> {
            handlers.sort(Comparator.comparing(MyAbstractChainHandler::getOrder));
        });
    }
}

chainContext 存储处理链及对应处理器列表,handler 方法执行链式处理,setApplicationContext 方法获取 Bean 实例,按链名分组并排序。

三、机制优势与应用

  1. 解耦性:各处理器逻辑独立,降低代码耦合度。
  2. 扩展性:方便添加新处理器,适应业务变化。
  3. 灵活性:可调整处理器顺序,改变处理流程。
  4. 可维护性:清晰的结构便于维护和调试。

在电商系统订单处理等复杂业务场景中,可将不同处理环节设为独立处理器,通过此机制实现高效处理。

相关推荐
烤麻辣烫3 分钟前
JS基础
开发语言·前端·javascript·学习
froginwe1113 分钟前
C++ 文件和流
开发语言
魂梦翩跹如雨17 分钟前
数据库的“契约” —— 约束(Constrains)
java·数据库·mysql
Dxy123931021631 分钟前
Python在图片上画矩形:从简单边框到复杂标注的全攻略
开发语言·python
独自破碎E43 分钟前
面试官:你有用过Java的流式吗?比如说一个列表.stream这种,然后以流式去处理数据。
java·开发语言
꯭爿꯭巎꯭43 分钟前
python下载手机版(python3手机版(免费))
开发语言·python·智能手机
网域小星球1 小时前
C++ 从 0 入门(六)|C++ 面试必知:运算符重载、异常处理、动态内存进阶(终极补充)
开发语言·c++·面试
胡志辉的博客1 小时前
多智能体协作,不是多开几个 Agent:从中介者模式看 OpenClaw 和 Hermes Agent
人工智能·设计模式·ai·agent·中介者模式·openclaw·herman
shark22222221 小时前
能懂!基于Springboot的用户增删查改(三层设计模式)
spring boot·后端·设计模式
2601_949818091 小时前
头歌答案--爬虫实战
java·前端·爬虫