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

样例代码

涉及到的项目样例代码均可以从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);
            }
        }
    }
}
相关推荐
会员果汁3 小时前
17.设计模式-单例模式(Singleton)
单例模式·设计模式
派大鑫wink3 小时前
【Day37】MVC 设计模式:原理与手动实现简易 MVC 框架
java·设计模式·mvc
会员果汁3 小时前
18.设计模式-桥接模式
设计模式·桥接模式
老蒋每日coding3 小时前
AI Agent 设计模式系列(九)——学习和适应模式
人工智能·学习·设计模式
da_vinci_x17 小时前
武器设计实战:一把大剑裂变 5 种属性?Structure Ref 的“换肤”魔法
游戏·3d·设计模式·ai作画·aigc·设计师·游戏美术
刀法孜然21 小时前
23种设计模式 3 行为型模式 之3.7 command 命令模式
设计模式·命令模式
一条闲鱼_mytube1 天前
智能体设计模式(二)反思-工具使用-规划
网络·人工智能·设计模式
老蒋每日coding1 天前
AI智能体设计模式系列(七)—— 多 Agent 协作模式
设计模式
小码过河.1 天前
设计模式——代理模式
设计模式·代理模式
Engineer邓祥浩1 天前
设计模式学习(14) 23-12 代理模式
学习·设计模式·代理模式