You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
---
|
|
|
|
观察者模式
|
|
|
|
---
|
|
|
|
|
|
|
|
#### 目录
|
|
|
|
|
|
|
|
1. 思维导图
|
|
|
|
2. 概述
|
|
|
|
3. 具体实现
|
|
|
|
4. 参考
|
|
|
|
|
|
|
|
#### 思维导图
|
|
|
|
|
|
|
|
#### 概述
|
|
|
|
|
|
|
|
观察者模式定义了对象间一种一对多的依赖关系,使得每当一个对象改变状态,则所有依赖它的对象都会得到通知并自动更新。它的最重要作用就是解耦,将被观察者和观察者解耦,使得它们之间的依赖性更小。
|
|
|
|
|
|
|
|
#### 具体实现
|
|
|
|
|
|
|
|
首先定义一个观察者的接口:
|
|
|
|
|
|
|
|
```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 收到通知!");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#### 参考
|