观察者模式:定义了对象之间的一对多依赖,这样一来,当一个对象改变时,
它的所有依赖者都会收到通知并自动更新。
实例解析:
建立一个应用,有三种布告板(温度、湿度、气压),分别显示目前的状况、气象统计及简单的天气预报。具体数据由Weather-O-Rama提供给
WeatherData对象。即:

自定义观察模式
类图设计:

//主函数代码
public class Main {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
weatherData.setMeasurements(80, 65, 30.4f);
weatherData.setMeasurements(82, 70, 29.2f);
weatherData.setMeasurements(78, 90, 29.2f);
}
}
Java内置观察模式
设计如下:

//主函数代码
public class main {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData);
weatherData.setMeasurements(80, 65, 30.4f);
weatherData.setMeasurements(82, 70, 29.2f);
weatherData.setMeasurements(78, 90, 29.2f);
}
}
设计原则
- 为了交互对象之间的松耦合设计而努力。
网友评论