观察者模式主要用于当一个对象发生改变时,其关联的所有对象都会收到通知,属于事件驱动类型的设计模式,可以对事件进行监听和响应。下面简单介绍下它的使用:
1 定义事件
import org.springframework.context.ApplicationEvent;
public class OrderCreatedEvent extends ApplicationEvent {
private final Long orderId;
public OrderCreatedEvent(Object source, Long orderId) {
super(source);
this.orderId = orderId;
}
public Long getOrderId() {
return orderId;
}
}
2 事件发布者
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private final ApplicationEventPublisher eventPublisher;
public OrderService(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void createOrder(Long orderId) {
// 创建订单逻辑
System.out.println("订单创建成功: " + orderId);
// 发布事件
eventPublisher.publishEvent(new OrderCreatedEvent(this, orderId));
}
}
3 事件监听者
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class NotificationService {
@EventListener
public void handleOrderCreated(OrderCreatedEvent event) {
System.out.println("发送通知:订单 " + event.getOrderId() + " 创建成功!");
}
}
注意事项:观察者模式只能在同一个微服务中使用,跨服务中将失效。



![[Windows] VutronMusic v1.6.0 音乐播放器纯净版,可登录同步](https://i-blog.csdnimg.cn/direct/793b84441fb04ecbb99bf79793baa199.png)







![STM32单片机入门学习——第3-4节: [2-1、2]软件安装和新建工程](https://i-blog.csdnimg.cn/direct/9ebb69abc1a741e6aa2a884c159e7f94.png)







