s.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);
}
}
}
package observer;
import java.util.*;
public class StatisticsDisplay implements Observer, DisplayElement {
private float maxTemp = 0.0f;
private float minTemp = 200;
private float tempSum= 0.0f;
private int numReadings;
private WeatherData 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);
}
}
4. 测试, 创建不同的
观察者(observer), 并把
主题(subject)作为参数传入, 通知观察者.
代码:
/**
* @time 2014年5月22日
*/
package observer;
/**
* @author C.L.Wang
*
*/
public class WeatherStation {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentConditionsDisplay =
new CurrentConditionsDisplay(weatherData); //new的时候进行注册
StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData);
ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData);
weatherData.setMeasurements(80, 65, 30.4f);
weatherData.setMeasurements(82, 70, 29.2f);
weatherData.setMeasurements(78, 90, 29.2f);
}
}
5. 输出:
Current conditions: 80.0F degrees and 65.0% humidity
Avg/Max/Min temperature = 80.0/80.0/80.0
Forecast: Improving weather on the way!
Current conditions: 82.0F degrees and 70.0% humidity
Avg/Max/Min temperature = 81.0/82.0/80.0
Forecast: Watch out for cooler, rainy weather
Current conditions: 78.0F degrees and 90.0% humidity
Avg/Max/Min temperature = 80.0/82.0/78.0
Forecast: More of the same
面向对象的原则:
为了交互对象之间的松耦合设计而努力.
