首先来看看观察者模式的概念:
定义对象间的一种一对多的依赖关系,当一个对象的状态发送改变时,所有依赖于它的对象都能得到通知并被自动更新
第一句可能不太懂,但是后面的容易懂,就像天气预报一样,只要你订阅了,他就会发短信更新通知你说天气变化了。这就是观察者。
观察者模式的成员:
1)、观察者。我们称之为Observer, 有时候我们也成他为订阅者,即Subscriber.
2)、被观察者:我们称之为Observable,即可用被观察的东西,有时候会成为主题,Subject
三部曲:
1、创建被观察者:注册(订阅),注销(取消订阅), 更新数据(Observable)


2、观察者:即Observer也叫Subscriber,在rxjava中Subscriber只是比Observer多了几个方法相对功能强大点

3、订阅、


二、在Android中的观察者:
1)、最简单的按钮点击事件(Button)
Button btn = new Button(this);
btn.setOnClickListener(new View.OnClickListener()){
public void onClick(View v){
Log.e("Tag", "click");
}
}
2)、RecycleView中的addOnScrollListener方法:滚动监听
3)、Android中自带的广播,广播通过registerReceiver注册广播,通过unregisterReceiver注销广播,通过sendBroadcast发送广播。这就是典型的观察者模式,
4)、开源框架EventBus也是基于观察者模式,观察者模式的三个典型,注册、取消注册,发送事件。

6)、当然最重量级的还是现在火热的RXjava,这个也是基于观察者模式。
①、创建被观察者:

②、观察者、即订阅者

③、观察者进行事件的订阅(被观察者订阅观察者)

具体的RXjava详解请查看这里Rxjava详细解析
支持原文创作:观察者模式
网友评论