基于《设计模式-使用策略模式+泛型 改造消息通知中心(一)》动态指定模板
设计模式-使用策略模式+泛型 改造消息通知中心(一)_长风千里的博客-CSDN博客
业务前置条件:
持久化存储消息模板,消息模板可配置化,并且消息模板中记录改模板使用消息策略的类型。
例如短信是1,微信模板消息是2。。。。具体怎么设计跟据业务实际情况来
改造如下:
模拟代码
Strategy抽象策略接口中增加判断模板类型的方法match
/**
* 抽象策略角色
* @param <T>
*/
public interface Strategy<T> {
/**
* 判断模板类型
* @param type
* @return
*/
boolean match(String type);
/**
* 发送消息
* @param t 发送消息的参数
* @return
*/
boolean send(T t);
}
具体策略实现
/**
*微信模板消息发送策略
* @author zenghao
* @version 1.0
* @date 2022/3/26 19:38
*/
public class WxStrategy implements Strategy<WxInfo> {
private static final String WX_TYPE = "2";
/**
* 传过来的是模板指定的策略类型
* @param type
* @return
*/
@Override
public boolean match(String type) {
return type==WX_TYPE?true :false;
}
@Override
public boolean send(WxInfo wxInfo) {
System.out.println("微信模板消息发送");
System.out.println("参数:"+wxInfo);
return true;
}
}
增加一个异步任务类,主要是增加异步发送消息的能力,不属于策略模式一环
/**
*异步发送消息
* @author zh
* @version 1.0
* @date 2022/3/26 22:39
*/
public class NoticeTask<T> implements Callable<Boolean> {
private Strategy strategy;
private String type;
private T t;
public NoticeTask(Strategy strategy, String type,T t) {
this.strategy = strategy;
this.type = type;
this.t = t;
}
@Override
public Boolean call() throws Exception {
Context<T> wxContext = new Context();
return wxContext.send(t,strategy);
}
}
上下文角色Context不变
/**
* 上下文角色
* @author zh
* @version 1.0
* @date 2022/3/26 19:40
*/
public class Context<T> {
public boolean send(T t, Strategy<T> strategy){
return strategy.send(t);
}
}
调用伪代码
/**
*发送消息
* @author zh
* @version 1.0
* @date 2022/3/26 22:29
*/
public class SpringDemo {
/**
* 这里包含了所有具体策略,只要实现了Strategy策略接口
*/
@Autowired
private Collection<Strategy> strategys;
@Autowired
private ExecutorService executorService;
public void sendMain(){
String type = "2"; //来源消息模板
//遍历策略,如果模板的类型和策略里面指定的类型匹配上,返回true,则执行改策略
strategys.forEach(item->{
//判断使用哪种策略,这个类型是消息模板里面配置指定的。
if(item.match(type)){
//开启线程池处理
//NoticeInfo是策略统一的参数
executorService.submit(new NoticeTask(item,type, new NoticeInfo("fere434334","87888frze","zh6666","账号下线通知")));
}
});
}
}
代码是盲敲的伪代码,细节上也许有点问题。但是整体思路是这样。