观察者模式

观察者模式UML结构图

首先,定义主题接口,观察者接口:

1
2
3
4
5
6
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
//当主题数据改变时,更新所有观察者的数据
public void notifyObservers();
}

观察者接口实现的是主题,让观察者得到的实时数据:

1
2
3
public interface Observer {
public void update(float temp, float humidity, float pressure);
}
1
2
3
public interface DisplayElement {
public void display();
}

然后创建被观察者对象,在被观察的对象里面管理观察者对象:

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.ArrayList;
import java.util.List;

public class WeatherData implements Subject {
private List<Observer> observerList = new ArrayList<>();
private float temperature;
private float humidity;
private float pressure;

@Override
public void registerObserver(Observer o) {
observerList.add(o);
}

@Override
public void removeObserver(Observer o) {
observerList.remove(o);
}

@Override
public void notifyObservers() {
for (Observer o : observerList) {
o.update(temperature, humidity, pressure);
}
}

public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}

public void measurementsChanged() {
notifyObservers();
}

public void setTemperature(float temperature) {
this.temperature = temperature;
}

public void setHumidity(float humidity) {
this.humidity = humidity;
}

public void setPressure(float pressure) {
this.pressure = pressure;
}
}

观察者的实例:

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
29
30
31
public class DisplayA implements Observer, Display {
private float temperature;
private float humidity;
private float pressure;
//主题
private Subject weatherData;

//将该观察者和weatherData对象绑定在一起
public DisplayA(Subject weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}

@Override
public void display() {
System.out.println("DisplayA{" +
"temperature=" + temperature +
", humidity=" + humidity +
", pressure=" + pressure +
'}');
}

//更新观测的数据
@Override
public void update(float temp, float humidity, float pressure) {
this.temperature = temp;
this.humidity = humidity;
this.pressure = pressure;
display();
}
}

测试类:

1
2
3
4
5
6
7
8
9
public class weatherStation {
public static void main(String[] args) {
Subject weatherData = new WeatherData();
Observer displayA = new DisplayA(weatherData);
((WeatherData) weatherData).setMeasurements(12, 23, 456);
((WeatherData) weatherData).setMeasurements(12, 23, 56);
((WeatherData) weatherData).setMeasurements(12, 23, 6);
}
}

当创建观察者实例时,引入订阅者对象,通知订阅者注册一个观察者。随后,订阅者的数据域发生改变,会同时调用存到list中的每一个实例去更新数据。

观察者模式的代表:MVC

联系我

评论