模式定义
观察者模式,定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
顾名思义,此模式需要有观察者(Observer)和被观察者(Observable)两类角色,当Observable状态变化时会通知Observer,Observer一般会实现一类通用的接口,比如java.util.Observer,Observable需要通知Observer时,逐个调用Observer的update方法即可,Observer的处理成功与否不应该影响Observable的流程。
使用场景
一个对象(Observable)状态改变需要通知其他对象,Observer的存在不影响Observable的处理结果,Observer的增删对Observable无感知,比如kafka的消息订阅,producer发送一条消息到topic,至于是1个还是10个consumer订阅这个topic,producer是不需要关注的。
实践经验
在Spring或者SpringBoot项目中,有时候需要在Spring容器启动并加载完之后,做一些系统初始化的事情。这时候,可以配置一个观察者ApplicationListener,来达到这一目的。这就是观察者模式的实践。
@Componentpublic class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {@Overridepublic void onApplicationEvent(ContextRefreshedEvent event) {System.out.println("干一些系统初始化的事情....");ApplicationContext context = event.getApplicationContext();String[] names = context.getBeanDefinitionNames();for (String beanName:names){System.out.println("----------"+beanName+"---------");}}}
首先,ApplicationContext是 Spring 中的核心容器。
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {//观察者容器private final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();//被观察者private ApplicationEventMulticaster applicationEventMulticaster;}
在ApplicationContext容器刷新的时候,会初始化一个被观察者,并注册到Spring容器中。
然后,注册各种观察者到被观察者中,形成一对多的依赖。
public abstract class AbstractApplicationContext{protected void registerListeners() {for (ApplicationListener<?> listener : getApplicationListeners()) {getApplicationEventMulticaster().addApplicationListener(listener);}String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);for (String listenerBeanName : listenerBeanNames) {getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);}Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;this.earlyApplicationEvents = null;if (earlyEventsToProcess != null) {for (ApplicationEvent earlyEvent : earlyEventsToProcess) {getApplicationEventMulticaster().multicastEvent(earlyEvent);}}}}
这时候,自定义的观察者对象也被注册到了applicationEventMulticaster里面。
最后,当ApplicationContext完成刷新后,则发布ContextRefreshedEvent事件。
protected void finishRefresh() {publishEvent(new ContextRefreshedEvent(this));}
通知观察者,调用ApplicationListener.onApplicationEvent()。
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {listener.onApplicationEvent(event);}
接下来再看看在Dubbo是如何应用这一机制的。
Dubbo服务导出过程始于 Spring 容器发布刷新事件,Dubbo 在接收到事件后,会立即执行服务导出逻辑。
public class ServiceBean<T> extends ServiceConfig<T> implements InitializingBean, DisposableBean,ApplicationContextAware, ApplicationListener<ContextRefreshedEvent>, BeanNameAware,ApplicationEventPublisherAware {@Overridepublic void onApplicationEvent(ContextRefreshedEvent event) {if (!isExported() && !isUnexported()) {if (logger.isInfoEnabled()) {logger.info("The service ready on spring started. service: " + getInterface());}export();}}}
可以看到,Dubbo中的ServiceBean也实现了ApplicationListener接口,在Spring容器发布刷新事件之后就会执行导出方法。重点关注在Dubbo执行完导出之后,它也发布了一个事件。
public class ServiceBean<T>{public void export() {super.export();publishExportEvent();}private void publishExportEvent() {ServiceBeanExportedEvent exportEvent = new ServiceBeanExportedEvent(this);applicationEventPublisher.publishEvent(exportEvent);}}
ServiceBeanExportedEvent,服务导出事件,需要继承Spring中的事件对象ApplicationEvent。
public class ServiceBeanExportedEvent extends ApplicationEvent {public ServiceBeanExportedEvent(ServiceBean serviceBean) {super(serviceBean);}public ServiceBean getServiceBean() {return (ServiceBean) super.getSource();}}
然后自定义一个ApplicationListener,也就是观察者,就可以监听到Dubbo服务接口导出事件了。
@Componentpublic class ServiceBeanListener implements ApplicationListener<ServiceBeanExportedEvent> {@Overridepublic void onApplicationEvent(ServiceBeanExportedEvent event) {ServiceBean serviceBean = event.getServiceBean();String beanName = serviceBean.getBeanName();Service service = serviceBean.getService();System.out.println(beanName+":"+service);}}
总结
观察者模式将被观察者和观察者之间做了解耦,观察者存在与否不会影响被观察者的现有逻辑。
