目的:
定义一种一对多的对象依赖关系这样当一个对象改变状态时,所有依赖它的对象都将自动通知或更新。
程序示例:
在遥远的土地上生活着霍比特人和兽人的种族。他们都是户外生活的人所以他们密切关注天气的变化。可以说他们不断地关注着天气。
1.定义天气类型合观察者接口
public enum WeatherType{
SUNNY("Sunny"),
RAINY("Rainy"),
WINDY("Windy"),
COLD("Cold");
private final String description;
WeatherType(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return this.name().toLowerCase();
}
}
public interface WeatherObserver{
void update(WeatherType currentWeather);
}
2.实现各种的观察者
@Slf4j
public class Orcs implements WeatherObserver{
@Override
public void update(WeatherType currentWeather) {
log.info("The orcs are facing " + currentWeather.getDescription() + " weather now");
}
}
@Slf4j
public class Hobbits implements WeatherObserver{
@Override
public void update(WeatherType currentWeather) {
log.info("The hobbits are facing " + currentWeather.getDescription() + " weather now");
}
}
3.观察对象
public class Weather{
private WeatherType currentWeather;
private final List<WeatherObserver> observers;
public Weather() {
currentWeather=WeatherType.SUNNY;
this.observers = new ArrayList<>();
}
//添加观察者
public void addObserver(WeatherObserver obs){
observers.add(obs);
}
//移除观察者
public void removeObserver(WeatherObserver obs){
observers.remove(obs);
}
//让时间随着天气流逝
public void timePasses(){
WeatherType[] weatherTypes = WeatherType.values();
//获取当前枚举的序号+1%长度 实现天气轮转
currentWeather=weatherTypes[(currentWeather.ordinal()+1)%weatherTypes.length];
notifyObservers();
}
//通知观察员
public void notifyObservers(){
observers.forEach(x->x.update(currentWeather));
}
}
4.测试输出
Weather weather = new Weather();
weather.addObserver(new Orcs());
Hobbits hobbits = new Hobbits();
weather.addObserver(hobbits);
weather.timePasses();
/*
The orcs are facing Rainy weather now
The hobbits are facing Rainy weather now
*/
weather.timePasses();
/*
The orcs are facing Windy weather now
The hobbits are facing Windy weather now
*/
weather.removeObserver(hobbits);
weather.timePasses();
/*
The orcs are facing Cold weather now
*/
weather.timePasses();
/*
The orcs are facing Sunny weather now
*/
类图: