目录
观察者模式定义
观察者模式定义:定义了对象之间一对多的依赖,让多个观察者对象同时监听一个主题对象,当主题对象发生变化时,它的所有依赖者都会收到通知并更新
适用场景:关联行为场景,建立一套触发的机制
优点:观察者和被观察者之间建立了一套抽象的耦合,支持广播通信
缺点:观察者之间有过多的细节依赖,提高了时间的消耗和程序的复杂度;使用时应该梳理清楚调用关系,避免重复调用
观察者模式使用案例
观察者模式在工作种使用较多,sring框架提供了spring event(spring 事件)来处理同一jvm的事件通知业务,注意是同一jvm。
SpringEvent的使用十分简单,核心内容为创建继承了ApplicationEvent的事件、调用ApplicationEventPublisher发送事件、接收者实现ApplicationListener方法接收事件。使用分为以下三个步骤:
声明事件(继承ApplicationEvent类)
public class UserRegisterEvent extends ApplicationEvent {
private static final long serialVersionUID = -4829855648590354032L;
public UserRegisterEvent(User user) {
super(user);
}
public User getUser() {
return (User) source;
}
}
发送事件(调用ApplicationEventPublisher的publishEvent方法发送事件)
@Autowired
private ApplicationEventPublisher publisher;
@Override
public void register(User user) throws Exception {
publisher.publishEvent(new UserRegisterEvent(user));
}
监听器接收事件(新建监听类,实现ApplicationListener接口,实现onApplicationEvent方法)
public class CouponListener implements ApplicationListener<UserRegisterEvent> {
@Override
public void onApplicationEvent(UserRegisterEvent event) {
System.out.println(event.getUser());
}
}
当被监听者发布事件后,监听者会收到事件。二者解耦,互相不需要关注业务是否处理成果。
spring-event 源码解析: springEvent 源码分析