观察者模式在源码中的使用

观察者模式定义对象间的一对多关系,当被观察者的状态发生改变时,所有观察者都会得到通知并进行相应操作。

下图是被观察的属性及方法:

 下图是观察者:

 在源码中的应用:

1.ContextLoaderListener继承servletContextListener,可以看出ContextLoaderListener为被观察者,ServletContextEvent是观察者。

 2.利用EventBus可以快速实现观察者模式

public class GavaEvent {
//观察者 @Subscribe
public void subscribe(String str){ System.out.println("thank you!"+str); } public static void main(String[] args) {
//EventBus被观察者 EventBus eventBus
= new EventBus(); GavaEvent gavaEvent = new GavaEvent(); eventBus.register(gavaEvent); eventBus.post("okhttp"); } }
原文地址:https://www.cnblogs.com/menbo/p/14071268.html