觀察者模式定義了一系列對象之間的一對多關系且轨,當一個對象(主題斋否,也稱被觀察者)改變狀態(tài),其他依賴者(觀察者)都會收到通知.
1.實例描述
現(xiàn)有負責追蹤天氣狀況(溫度乏矾,濕度,氣壓)的WeatherData對象迁杨,利用該對象建立一個氣象觀測站應用钻心,有三種布告板,分別顯示目前的狀況铅协,氣象統(tǒng)計及簡單的預報捷沸,當WeatherData里面有最新的數(shù)據(jù)測量時,三種布告板必段實時更新狐史。并要求我們能靈活的增加觀察者痒给,移除觀察者。同時在布告板的塊數(shù)可能增加骏全,如增加酷熱指數(shù)布告板苍柏。
2.分析思路
根據(jù)定義和描述,我們可以將WeatherDate作為主題姜贡,三塊布告板作為觀察者试吁。首先創(chuàng)建Subjec接口,里面定義添加楼咳,移除潘悼,通知觀察者功能,實現(xiàn)該接口的WeatherData通過ArrayList字段來模擬所有觀察者爬橡,還有溫度治唤,濕度,氣壓字段糙申,實現(xiàn)接口的方法宾添。然后創(chuàng)建Observer接口,定義更新功能,由于每個布告板還有不同的展示方式缕陕,我們還需創(chuàng)建一個DispayElement接口粱锐,里面定義展示行為。所有的布告板都實現(xiàn)了Observer和DispayElement接口扛邑,并且定義了私有的Subject和相關私有字段怜浅。
WeatherData里面實現(xiàn)了注冊和移除觀察者的方法。當要增加一個布告板時蔬崩,我們只需要實現(xiàn)Observer,DisplayElement兩個接口恶座,并且注冊。
3.類圖實現(xiàn)
主題:
觀察者:
4.代碼實現(xiàn)
Subject:主題接口
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}
WeatherData:主題的具體實現(xiàn)
import java.util.*;
public class WeatherData implements Subject {
private ArrayList observers;
private float temperature;
private float humidity;
private float pressure;
public WeatherData() {
observers = new ArrayList();
}
public void registerObserver(Observer o) {
observers.add(o);
}
public void removeObserver(Observer o) {
int i = observers.indexOf(o);
if (i >= 0) {
observers.remove(i);
}
}
public void notifyObservers() {
for (int i = 0; i < observers.size(); i++) {
Observer observer = (Observer)observers.get(i);
observer.update(temperature, humidity, pressure);
}
}
public void measurementsChanged() {
notifyObservers();
}
public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}
// other WeatherData methods here
public float getTemperature() {
return temperature;
}
public float getHumidity() {
return humidity;
}
public float getPressure() {
return pressure;
}
}
Observer:觀察者核心接口
public interface Observer {
public void update(float temp, float humidity, float pressure);
}
** DisplayElement:**布告板展示行為的接口
public interface DisplayElement {
public void display();
}
CurrentConditionsDisplay:觀察者1沥阳,即提供目前狀況的布告板
public class CurrentConditionsDisplay implements Observer, DisplayElement {
private float temperature;
private float humidity;
private Subject weatherData;
public CurrentConditionsDisplay(Subject weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
public void update(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
display();
}
public void display() {
System.out.println("Current conditions: " + temperature
+ "F degrees and " + humidity + "% humidity");
}
}
StatisticsDisplay:觀察者2跨琳,即提供氣象統(tǒng)計的布告板
public class StatisticsDisplay implements Observer, DisplayElement {
private float maxTemp = 0.0f;
private float minTemp = 200;
private float tempSum = 0.0f;
private int numReadings;
private Subject weatherData;
public StatisticsDisplay(WeatherData weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
public void update(float temp, float humidity, float pressure) {
tempSum += temp;
numReadings++;
if (temp > maxTemp) {
maxTemp = temp;
}
if (temp < minTemp) {
minTemp = temp;
}
display();
}
public void display() {
System.out.println("Avg/Max/Min temperature = "
+ (tempSum / numReadings) + "/" + maxTemp + "/" + minTemp);
}
}
**ForecastDisplay: **觀察者3,即提供簡單預報功能的布告板
public class ForecastDisplay implements Observer, DisplayElement {
private float currentPressure = 29.92f;
private float lastPressure;
private Subject weatherData;
public ForecastDisplay(WeatherData weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
public void update(float temp, float humidity, float pressure) {
lastPressure = currentPressure;
currentPressure = pressure;
display();
}
public void display() {
System.out.print("Forecast: ");
if (currentPressure > lastPressure) {
System.out.println("Improving weather on the way!");
} else if (currentPressure == lastPressure) {
System.out.println("More of the same");
} else if (currentPressure < lastPressure) {
System.out.println("Watch out for cooler, rainy weather");
}
}
}
HeatIndexDisplay:觀察者4,即新增加的提供酷熱指數(shù)的布告板
public class HeatIndexDisplay implements Observer, DisplayElement {
float heatIndex = 0.0f;
private Subject weatherData;
public HeatIndexDisplay(WeatherData weatherData) {
this.weatherData = weatherData;
weatherData.registerObserver(this);
}
public void update(float t, float rh, float pressure) {
heatIndex = computeHeatIndex(t, rh);
display();
}
private float computeHeatIndex(float t, float rh) {
float index = (float) ((16.923 + (0.185212 * t) + (5.37941 * rh)
- (0.100254 * t * rh) + (0.00941695 * (t * t))
+ (0.00728898 * (rh * rh)) + (0.000345372 * (t * t * rh))
- (0.000814971 * (t * rh * rh))
+ (0.0000102102 * (t * t * rh * rh))
- (0.000038646 * (t * t * t)) + (0.0000291583 * (rh * rh * rh))
+ (0.00000142721 * (t * t * t * rh))
+ (0.000000197483 * (t * rh * rh * rh))
- (0.0000000218429 * (t * t * t * rh * rh)) + 0.000000000843296 * (t
* t * rh * rh * rh)) - (0.0000000000481975 * (t * t * t * rh
* rh * rh)));
return index;
}
public void display() {
System.out.println("Heat index is " + heatIndex);
}
}