觀察者模式:定義了對象之間的一對多依賴太闺,這樣一來,當(dāng)一個對象改變時枢贿,
它的所有依賴者都會收到通知并自動更新殉农。
實例解析:
建立一個應(yīng)用,有三種布告板(溫度局荚、濕度超凳、氣壓),分別顯示目前的狀況、氣象統(tǒng)計及簡單的天氣預(yù)報聪建。具體數(shù)據(jù)由Weather-O-Rama提供給
WeatherData對象钙畔。即:
自定義觀察模式
類圖設(shè)計:
//主函數(shù)代碼
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內(nèi)置觀察模式
設(shè)計如下:
//主函數(shù)代碼
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);
}
}
設(shè)計原則
- 為了交互對象之間的松耦合設(shè)計而努力。