当前位置: 首页> 游戏> 单机 > 哈尔滨专业优化网站个人_网推app有哪些_semir是什么牌子衣服_百度广告业务

哈尔滨专业优化网站个人_网推app有哪些_semir是什么牌子衣服_百度广告业务

时间:2025/7/10 4:30:26来源:https://blog.csdn.net/shenxiaomo1688/article/details/146882563 浏览次数:2次
哈尔滨专业优化网站个人_网推app有哪些_semir是什么牌子衣服_百度广告业务

观察者模式主要用于当一个对象发生改变时,其关联的所有对象都会收到通知,属于事件驱动类型的设计模式,可以对事件进行监听和响应。下面简单介绍下它的使用:

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 {@EventListenerpublic void handleOrderCreated(OrderCreatedEvent event) {System.out.println("发送通知:订单 " + event.getOrderId() + " 创建成功!");}
}

注意事项:观察者模式只能在同一个微服务中使用,跨服务中将失效。

关键字:哈尔滨专业优化网站个人_网推app有哪些_semir是什么牌子衣服_百度广告业务

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: