1.观察者模式基本概念
一个对象状态改变,通知给其他所有的对象
2.观察者模式的应用场景
- Zk的事件监听
- 分布式配置中心刷新配置文件
- 业务中群发不同渠道消息
3. 观察者模式的类图
4.代码示例
4.1 定义Observer接口
/**
* @author tostyle
* 2022/4/8 13:26
*/
public interface ObServer {
/**
* 发送消息
* @param jsonObject
*/
void sendMsg(JSONObject jsonObject);
}
/**
* @author tostyle
* 2022/4/8 13:27
*/
@Component
@Slf4j
public class EmailObServer implements ObServer {
@Override
public void sendMsg(JSONObject jsonObject) {
log.info("邮件发送观察者监听");
}
}
/**
* @author tostyle
* 2022/4/8 13:28
*/
@Component
@Slf4j
public class SmsObServer implements ObServer {
@Override
public void sendMsg(JSONObject jsonObject) {
log.info("短信发送观察者监听");
}
}
4.2主题通知所有观察者
/**
* @author tostyle
* 2022/4/8 13:31
*/
@Component
public class NotifySubject {
/**
* 类型 ObServer
*/
private List<ObServer> listObServer = new ArrayList<>();
/**
* 线程池
*/
private ExecutorService executorService;
public NotifySubject() {
executorService = Executors.newFixedThreadPool(10);
}
/**
* 新增ObServer
*
* @param obServer
*/
public void addObServer(ObServer obServer) {
listObServer.add(obServer);
}
/**
* 通知给所有的观察者
*
* @param jsonObject
*/
public void notifyObServer(JSONObject jsonObject) {
for (ObServer obServer :
listObServer) {
// 单独开启线程异步通知
executorService.execute(() -> obServer.sendMsg(jsonObject));
}
}
}
4.3项目启动注册观察者
/**
* @author tostyle
* 2022/4/8 13:33
*/
@Component
public class StartService implements ApplicationRunner, ApplicationContextAware {
@Autowired
private NotifySubject notifySubject;
private ApplicationContext applicationContext;
@Override
public void run(ApplicationArguments args) throws Exception {
//通过接口获取对应的子类
Map<String, ObServer> map = applicationContext.getBeansOfType(ObServer.class);
for (String key : map.keySet()) {
ObServer obServer = map.get(key);
notifySubject.addObServer(obServer);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
}
}
4.4 测试
/**
* @author tostyle
* 2022/4/8 13:38
*/
@RestController
@Slf4j
public class OrderController {
@Autowired
private NotifySubject notifySubject;
@RequestMapping("/addOrder")
public String addOrder() {
log.info("1.调用数据库下单订单代码:");
JSONObject jsonObject = new JSONObject();
jsonObject.put("sms", "1865891111");
jsonObject.put("email", "644064779@qq.com");
notifySubject.notifyObServer(jsonObject);
return "success";
}
}
4.5 代码地址
https://gitee.com/todostyle/springcloud.git