观察者设计模式

模式定义

观察者模式,定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
顾名思义,此模式需要有观察者(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,来达到这一目的。这就是观察者模式的实践。

  1. @Component
  2. public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
  3. @Override
  4. public void onApplicationEvent(ContextRefreshedEvent event) {
  5. System.out.println("干一些系统初始化的事情....");
  6. ApplicationContext context = event.getApplicationContext();
  7. String[] names = context.getBeanDefinitionNames();
  8. for (String beanName:names){
  9. System.out.println("----------"+beanName+"---------");
  10. }
  11. }
  12. }

首先,ApplicationContext是 Spring 中的核心容器。

  1. public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
  2. //观察者容器
  3. private final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();
  4. //被观察者
  5. private ApplicationEventMulticaster applicationEventMulticaster;
  6. }

在ApplicationContext容器刷新的时候,会初始化一个被观察者,并注册到Spring容器中。
然后,注册各种观察者到被观察者中,形成一对多的依赖。

  1. public abstract class AbstractApplicationContext{
  2. protected void registerListeners() {
  3. for (ApplicationListener<?> listener : getApplicationListeners()) {
  4. getApplicationEventMulticaster().addApplicationListener(listener);
  5. }
  6. String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
  7. for (String listenerBeanName : listenerBeanNames) {
  8. getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
  9. }
  10. Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
  11. this.earlyApplicationEvents = null;
  12. if (earlyEventsToProcess != null) {
  13. for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
  14. getApplicationEventMulticaster().multicastEvent(earlyEvent);
  15. }
  16. }
  17. }
  18. }

这时候,自定义的观察者对象也被注册到了applicationEventMulticaster里面。
最后,当ApplicationContext完成刷新后,则发布ContextRefreshedEvent事件。

  1. protected void finishRefresh() {
  2. publishEvent(new ContextRefreshedEvent(this));
  3. }

通知观察者,调用ApplicationListener.onApplicationEvent()。

  1. private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
  2. listener.onApplicationEvent(event);
  3. }

接下来再看看在Dubbo是如何应用这一机制的。
Dubbo服务导出过程始于 Spring 容器发布刷新事件,Dubbo 在接收到事件后,会立即执行服务导出逻辑。

  1. public class ServiceBean<T> extends ServiceConfig<T> implements InitializingBean, DisposableBean,
  2. ApplicationContextAware, ApplicationListener<ContextRefreshedEvent>, BeanNameAware,
  3. ApplicationEventPublisherAware {
  4. @Override
  5. public void onApplicationEvent(ContextRefreshedEvent event) {
  6. if (!isExported() && !isUnexported()) {
  7. if (logger.isInfoEnabled()) {
  8. logger.info("The service ready on spring started. service: " + getInterface());
  9. }
  10. export();
  11. }
  12. }
  13. }

可以看到,Dubbo中的ServiceBean也实现了ApplicationListener接口,在Spring容器发布刷新事件之后就会执行导出方法。重点关注在Dubbo执行完导出之后,它也发布了一个事件。

  1. public class ServiceBean<T>{
  2. public void export() {
  3. super.export();
  4. publishExportEvent();
  5. }
  6. private void publishExportEvent() {
  7. ServiceBeanExportedEvent exportEvent = new ServiceBeanExportedEvent(this);
  8. applicationEventPublisher.publishEvent(exportEvent);
  9. }
  10. }

ServiceBeanExportedEvent,服务导出事件,需要继承Spring中的事件对象ApplicationEvent。

  1. public class ServiceBeanExportedEvent extends ApplicationEvent {
  2. public ServiceBeanExportedEvent(ServiceBean serviceBean) {
  3. super(serviceBean);
  4. }
  5. public ServiceBean getServiceBean() {
  6. return (ServiceBean) super.getSource();
  7. }
  8. }

然后自定义一个ApplicationListener,也就是观察者,就可以监听到Dubbo服务接口导出事件了。

  1. @Component
  2. public class ServiceBeanListener implements ApplicationListener<ServiceBeanExportedEvent> {
  3. @Override
  4. public void onApplicationEvent(ServiceBeanExportedEvent event) {
  5. ServiceBean serviceBean = event.getServiceBean();
  6. String beanName = serviceBean.getBeanName();
  7. Service service = serviceBean.getService();
  8. System.out.println(beanName+":"+service);
  9. }
  10. }

总结

观察者模式将被观察者和观察者之间做了解耦,观察者存在与否不会影响被观察者的现有逻辑。