观察者模式
当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知依赖它的对象。观察者模式属于行为型模式。
示例演示:
我们创建一个观察者的抽象类observer和被观察的对象people
1
2
3
4
5
6
7
8package test.observer;
public abstract class Observer {
protected People people;
public abstract void update(int status);
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29package test.observer;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
public class People {
private List<Observer> observers = new ArrayList<>();
private int status;
public void setStatus(int status) {
this.status = status;
this.notifyAll(status);
}
public void add(Observer observer) {
observers.add(observer);
}
public void notifyAll(int status) {
for (Observer observer : observers) {
observer.update(status);
}
}
}创建三个观察者对象
1
2
3
4
5
6
7
8
9
10
11
12
13package test.observer;
public class ObserverOne extends Observer {
public ObserverOne(People people) {
this.people = people;
this.people.add(this);
}
public void update(int status) {
System.out.println("ObserverOne status change: " + people.getStatus());
}
}1
2
3
4
5
6
7
8
9
10
11
12
13package test.observer;
public class ObserverTwo extends Observer {
public ObserverTwo(People people) {
this.people = people;
people.add(this);
}
public void update(int status) {
System.out.println("ObserverTwo status change: " + people.getStatus());
}
}1
2
3
4
5
6
7
8
9
10
11
12
13package test.observer;
public class ObserverThree extends Observer {
public ObserverThree(People people) {
this.people = people;
people.add(this);
}
public void update(int status) {
System.out.println("ObserverThree status change: " + people.getStatus());
}
}完成上述步骤,我们就可以开始演示了
1
2
3
4
5
6
7
8
9
10
11
12
13
14package test.observer;
public class ObserverDemo {
public static void main(String[] args) {
People people = new People();
new ObserverOne(people);
new ObserverTwo(people);
new ObserverThree(people);
people.setStatus(1);
System.out.println("---------------------------------");
people.setStatus(2);
}
}运行结果:
1
2
3
4
5
6
7ObserverOne status change: 1
ObserverTwo status change: 1
ObserverThree status change: 1
---------------------------------
ObserverOne status change: 2
ObserverTwo status change: 2
ObserverThree status change: 2
说明:
优点: 1、观察者和被观察者是抽象耦合的。 2、建立一套触发机制。
缺点: 1、如果一个被观察者对象有很多的直接和间接的观察者的话,将所有的观察者都通知到会花费很多时间。 2、如果在观察者和观察目标之间有循环依赖的话,观察目标会触发它们之间进行循环调用,可能导致系统崩溃。 3、观察者模式没有相应的机制让观察者知道所观察的目标对象是怎么发生变化的,而仅仅只是知道观察目标发生了变化。