public class 观察者模式 {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
currentConditionDisplay c = new currentConditionDisplay(weatherData);
weatherData.setMeasurements(1, 2, 3);
}
}
class WeatherData extends Observable {
private float temperature;
private float humidity;
private float pressure;
public WeatherData() {
}
public void measurementChanged() {
setChanged();
notifyObservers();
}
public void setMeasurements(float temperature, float humidity, float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementChanged();
}
public float getTemperature() {
return temperature;
}
public float getHumidity() {
return humidity;
}
public float getPressure() {
return pressure;
}
}
class currentConditionDisplay implements Observer {
Observable observable;
private float temperature;
private float humidity;
public currentConditionDisplay(Observable o) {
this.observable = o;
observable.addObserver(this);
}
@Override
public void update(Observable o, Object arg) {
if (o instanceof WeatherData) {
WeatherData weatherData = (WeatherData) o;
this.temperature = weatherData.getTemperature();
this.humidity = weatherData.getHumidity();
System.out.println("temperature:" + temperature + " humidity:" + humidity);
}
}
}