在一个实现通知功能的接口中,通常用一个通知类型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);
}
}复制代码