重构 - 观察者模式

在一个实现通知功能的接口中,通常用一个通知类型notifyType来区别不同的业务场景,然后用switch来划分不同的逻辑流向。

String notifyType = "";
switch (notifyType) {
    case "类型1":
        doType1();  // 逻辑1
        break;
    case "类型2":
        doType2();  // 逻辑2
        break;
}复制代码

但这样扩展性不好,当新增一个通知类型(eg:类型3),则需要修改switch方法,违背了开放封闭原则。这时可以用观察者模式来进行改造。


观察者模式原理在此不再做阐述,具体实现如下:

1. 定义一个抽象的通知监听器接口

public interface NotifyReqListener {
    /** 具体执行函数 **/
    boolean action(NotifyReq notifyReq);
}
复制代码


2. 定义一个监听者注册类

@Component
public class NotifyReqListenerRegistry {
  
    // 建立通知类型与监听器之间的映射关系
    private Map<String, NotifyReqListener> listenerMap = new ConcurrentHashMap<String, NotifyReqListener>();

    // 添加监听器
    public void addListener(String notifyType, NotifyReqListener listener) {
        if (listener != null && notifyType != null) {
            listenerMap.put(notifyType, listener);
	}
    }

    // 通过通知类型获取指定的监听器
    public NotifyReqListener getListener(String notifyType) {
        return listenerMap.get(notifyType);
    }
}复制代码


3. 当新增一个通知类型时,只要往监听器注册即可。

NotifyReqListener listener = notifyReqListenerRegistry.getListener(notifyReq.getNotifyType());
if (listener != null) {
    res = listener.action(notifyReq);
} else {
    logger.error("getNotifyType invalid {}", notifyReq);
}复制代码


4. 假设现在新增一个通知类型newType

String newNotifyType = "newType";复制代码

只需创建一个监听类,实现NotifyReqListener接口,然后重写action,实现自己的业务逻辑。

@Component
public class NewTypeListener implements NotifyReqListener {

    private NotifyReqListenerRegistry registry;    

    @Override
    public boolean action(NotifyReq notifyReq) {
        // 重写action,实现newType的业务逻辑  }

  public NotifyReqListenerRegistry getRegistry() {
        return registry;
  }

  @Autowired
  public void setRegistry(NotifyReqListenerRegistry registry) {
        this.registry = registry;
        // 将新的通知类型注册到监听器
	registry.addListener("newType", this);
  }
}复制代码


转载于:https://juejin.im/post/5b0e3c64518825157f4b9a6b

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值