menbbo

导航

 

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

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

 

 下图是观察者:

 

 在源码中的应用:

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"); } }

 

posted on 2020-12-01 22:33  menbbo  阅读(165)  评论(0编辑  收藏  举报