还是和push一样,有个主题WeatherData.java的类
import java.util.Observable; public class WeatherData extends Observable { private float temperature; private float humidity; private float pressure; public WeatherData(){} public void measurementsChanged() { setChanged(); notifyObservers(); } public void setMeasurements(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; measurementsChanged(); } public float getTemperature() { return temperature; } public float getHumidity() { return humidity; } public float getPressure() { return pressure; } }
请注意:这里的WeahterData.java继承的是java.util.Observable
在Observable方法中
setChanged();方法把changed设置为true;
notifyObservers();方法只有在changed为true的时候才去通知观察者。
接下来是观察者对象:CurrentConditionsDisplay.java对象。
import java.util.Observable; import java.util.Observer; import org.inter.DisplayElement; public class CurrentConditionsDisplay implements Observer, DisplayElement{ Observable observable; private float temperature; private float humidity; public CurrentConditionsDisplay(Observable observable) { this.observable = observable; observable.addObserver(this); } public void update(Observable o, Object arg) { // TODO Auto-generated method stub if(o instanceof WeatherData) { WeatherData weatherData = (WeatherData) o; this.temperature = weatherData.getTemperature(); this.humidity = weatherData.getHumidity(); display(); } } public void display() { // TODO Auto-generated method stub System.out.println(temperature + " : " + humidity); } }
同push同样的方法来验证:
public class PushWeatherStation { public static void main(String[] args) { WeatherData wd = new WeatherData(); CurrentConditionsDisplay display = new CurrentConditionsDisplay(wd); wd.setMeasurements(80, 65, 30.4f); wd.setMeasurements(10, 25, 30.4f); } }