贯穿设计模式-责任链模式

样例代码

涉及到的项目样例代码均可以从https://github.com/WeiXiao-Hyy/Design-Patterns.git获取

需求

实时地,根据city,sex,product字段进行业务投放,比如:北京的男生;四川的电脑等等 → 责任链模式(责任链表模式)

UML图

handler自身含有next指针和链表类似,使用Apollo进行动态配置字段进行规则变更

Apollo访问不到内网地址

由于Apollo使用Docker进行安装,导致Apollo访问不到configserver的地址

bash 复制代码
app:
  id: DesignPatternLearning

# apollo
apollo:
  meta: "http://localhost:8080"
  bootstrap:
    enabled: true
    eagerLoad:
      enabled: true
  cacheDir:
    "/Users/hujiale/GitCode/Apoll"

logger:
  level:
    com:
      info

执行时在JVM参数添加-Dapollo.configService=http://localhost:8080即可解决

核心代码

java 复制代码
//组装责任链条并返回责任链条首节点
private AbstractBusinessHandler buildChain() {

    //如果没有配置,直接返回null
    if (Objects.isNull(this.handlerType)) {
        return null;
    }

    if (Objects.isNull(this.currentHandlerType)) {
        this.currentHandlerType = this.handlerType;
    }

    if (this.currentHandlerType.equals(this.handlerType) && Objects.nonNull(this.currentHandler)) {
        return this.currentHandler;
    } else {
        log.info("config modified or first init, start to assemble duty chain.");
        synchronized (this) {
            try {
                //伪头节点
                AbstractBusinessHandler dummyHeadHandler = new CityHandler();
                AbstractBusinessHandler preHandler = dummyHeadHandler;

				//采用反射实例化责任链节点
                String[] handlerTypeList = this.handlerType.split(",");
                for (String handlerType : handlerTypeList) {
                    AbstractBusinessHandler handler = (AbstractBusinessHandler)
                            Class.forName(HandlerEnum.valueOf(handlerType).getValue()).newInstance();
                    preHandler.nextHandler = handler;
                    preHandler = handler;
                }
                
				// 初始化类中变量
                this.currentHandler = dummyHeadHandler.nextHandler;
                this.currentHandlerType = this.handlerType;

                return this.currentHandler;
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                throw new UnsupportedOperationException(e);
            }
        }
    }
}
相关推荐
未若君雅裁2 小时前
责任链模式详解:从Servlet过滤器到订单创建流程
servlet·责任链模式
石一峰6997 小时前
C 语言函数设计模式实战经验
c语言·开发语言·设计模式
qq_297574679 小时前
设计模式系列文章(基础篇第22篇):访问者模式——分离数据结构与操作,实现灵活扩展
数据结构·设计模式·访问者模式
许彰午12 小时前
责任链模式实战——同一个框架里的两种链
java·开发语言·责任链模式
刀法如飞16 小时前
领域驱动 vs 本体驱动:DDD 代码建模与 Ontology 语义建模的对比分析
设计模式·架构设计·领域驱动
我爱cope1 天前
【Agent智能体26 | 多智能体-多智能体工作流】
人工智能·设计模式·语言模型·职场和发展
咖啡八杯1 天前
【无标题】
java·后端·设计模式
折哥的程序人生 · 物流技术专研2 天前
Java 23 种设计模式:从踩坑到精通 | 适配器模式 —— 让不兼容的接口也能一起工作
java·设计模式·面试·适配器模式·单一职责原则
布朗克1682 天前
33 设计模式精讲
java·单例模式·设计模式