|
|
|
---
|
|
|
|
观察者模式
|
|
|
|
---
|
|
|
|
|
|
|
|
#### 目录
|
|
|
|
|
|
|
|
1. 思维导图
|
|
|
|
2. 概述
|
|
|
|
3. 常见实现例子
|
|
|
|
4. 具体实现
|
|
|
|
5. 参考
|
|
|
|
|
|
|
|
#### 思维导图
|
|
|
|
|
|
|
|
#### 概述
|
|
|
|
|
|
|
|
观察者模式定义了对象间一种一对多的依赖关系,使得每当一个对象改变状态,则所有依赖它的对象都会得到通知并自动更新。它的最重要作用就是解耦,将被观察者和观察者解耦,使得它们之间的依赖性更小。
|
|
|
|
|
|
|
|
#### 常见实现例子
|
|
|
|
|
|
|
|
1. 常见的发布订阅模式
|
|
|
|
2. ListView 的 Adapter 的 notifyDataSetChanged
|
|
|
|
3. BroadcastReceiver
|
|
|
|
4. EventBus
|
|
|
|
5. RxJava
|
|
|
|
|
|
|
|
#### 具体实现
|
|
|
|
|
|
|
|
首先定义一个观察者的接口:
|
|
|
|
|
|
|
|
```java
|
|
|
|
public interface Observer {
|
|
|
|
void onUpdate();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
然后具体的观察者实现:
|
|
|
|
|
|
|
|
```java
|
|
|
|
public class Observer1 implements Observer {
|
|
|
|
@Override
|
|
|
|
public void onUpdate() {
|
|
|
|
System.out.println("Observer1 收到通知!");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
```java
|
|
|
|
public class Observer2 implements Observer {
|
|
|
|
@Override
|
|
|
|
public void onUpdate() {
|
|
|
|
System.out.println("Observer2 收到通知!");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
在创建一个被观察者对象接口:
|
|
|
|
|
|
|
|
```java
|
|
|
|
public interface Subject {
|
|
|
|
/**
|
|
|
|
* 添加观察者
|
|
|
|
*/
|
|
|
|
void add(Observer observer);
|
|
|
|
/**
|
|
|
|
* 删除观察者
|
|
|
|
*/
|
|
|
|
void delete(Observer observer);
|
|
|
|
/**
|
|
|
|
* 通知所有观察者
|
|
|
|
*/
|
|
|
|
void notifyAllObservers();
|
|
|
|
/**
|
|
|
|
* 自身的操作
|
|
|
|
*/
|
|
|
|
void operation();
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
抽象主题:
|
|
|
|
|
|
|
|
```java
|
|
|
|
public abstract class AbstractSubject implements Subject {
|
|
|
|
|
|
|
|
private Vector<Observer> vector = new Vector<>();
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void add(Observer observer) {
|
|
|
|
vector.add(observer);
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void delete(Observer observer) {
|
|
|
|
vector.remove(observer);
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void notifyAllObservers() {
|
|
|
|
Enumeration<Observer> enumeration = vector.elements();
|
|
|
|
while (enumeration.hasMoreElements()) {
|
|
|
|
enumeration.nextElement().onUpdate();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
具体的观察者对象:
|
|
|
|
|
|
|
|
```java
|
|
|
|
public class MySubject extends AbstractSubject {
|
|
|
|
@Override
|
|
|
|
public void operation() {
|
|
|
|
System.out.println("执行更新!");
|
|
|
|
notifyAllObservers();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
测试:
|
|
|
|
|
|
|
|
```java
|
|
|
|
public class ObserverTest {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
MySubject mySubject = new MySubject();
|
|
|
|
mySubject.add(new Observer1());
|
|
|
|
mySubject.add(new Observer2());
|
|
|
|
mySubject.operation();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#### 参考
|
|
|
|
|
|
|
|
[Observer(观察者模式)](https://github.com/jeanboydev/Android-ReadTheFuckingSourceCode/blob/master/article/design_patterns/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-Observer.md)
|