定义
观察者模式定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖者都会受到通知并自动更新
使用场景
- 当一个抽象有两个方面,一个依赖于另一个。 将这些方面封装在单独的对象中,可以单独更改和重复使用它们
- 当对一个对象的更改需要更改其他对象时,并且你不知道有多少对象需要更改
- 当一个对象应该能够通知其他对象而不假设这些对象是谁。 换句话说,你不希望这些对象紧密耦合
例子
一个简单的天气预报的例子:
public interface WeatherObserver {
void update(WeatherType currentWeather);
}
public enum WeatherType {
SUNNY, RAINY, WINDY, COLD;
@Override
public String toString() {
return this.name().toLowerCase();
}
}
// 发布者
public class Weather {
private WeatherType currentWeather;
private List<WeatherObserver> observers;
public Weather() {
observers = new ArrayList<>();
currentWeather = WeatherType.SUNNY;
}
public void addObserver(WeatherObserver obs) {
observers.add(obs);
}
public void removeObserver(WeatherObserver obs) {
observers.remove(obs);
}
public void timePasses() {
WeatherType[] enumValues = WeatherType.values();
currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];
System.out.println("The weather changed to " + currentWeather + ".");
notifyObservers();
}
private void notifyObservers() {
for (WeatherObserver obs : observers) {
obs.update(currentWeather);
}
}
}
// 两个观察者
public class Hobbits implements WeatherObserver {
@Override
public void update(WeatherType currentWeather) {
switch (currentWeather) {
case COLD:
System.out.println("The hobbits are shivering in the cold weather.");
break;
case RAINY:
System.out.println("The hobbits look for cover from the rain.");
break;
case SUNNY:
System.out.println("The happy hobbits bade in the warm sun.");
break;
case WINDY:
System.out.println("The hobbits hold their hats tightly in the windy weather.");
break;
default:
break;
}
}
}
public class Orcs implements WeatherObserver {
@Override
public void update(WeatherType currentWeather) {
switch (currentWeather) {
case COLD:
System.out.println("The orcs are freezing cold.");
break;
case RAINY:
System.out.println("The orcs are dripping wet.");
break;
case SUNNY:
System.out.println("The sun hurts the orcs' eyes.");
break;
case WINDY:
System.out.println("The orc smell almost vanishes in the wind.");
break;
default:
break;
}
}
}
// 测试
public class App {
public static void main(String[] args) {
Weather weather = new Weather();
weather.addObserver(new Orcs());
weather.addObserver(new Hobbits());
weather.timePasses();
weather.timePasses();
}
}
分析
观察者模式体现了为了交互对象之间的松耦合设计而努力的设计原则!
网友评论