马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
利用java内置的观察者的话,我们不再需要追踪观察者了,也不需要管理注册与删除(让父类代劳即可)。所以我们把注册,添加,通知的代码都删除。
package com.godinsec;
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(); //在调用notifyObservers()之前,要先调用setChanged()来指示状态已经改变
}
public void setMeasurements(float temperature, float humidity, float pressure){
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}
//这些并不是新方法,只是因为我们要使用“拉”的做法,所以才提醒你有这些方法。观察者会利用这些方法取得WeatherData对象的状//态。
public float getTemperature(){
return temperature;
}
public float getHumidity(){
return humidity;
}
public float getPressure(){
return pressure;
}
}
观察者的做法:package com.godinsec;
import java.util.Observable;
import java.util.Observer;
public class CurrentConditionsDisplay implements Observer,DisplayElement{
Observable observable;
private float temperature;
private float humidity;
private float pressure;
public CurrentConditionsDisplay(Observable observable){
this.observable = observable;
observable.addObserver(this);
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("Current conditions: " + temperature +
"F degrees and" + humidity + "% humidity");
}
@Override
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();
this.pressure = weatherData.getPressure();
display();
}
}
}
测试类:package com.godinsec;
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);
weatherData.setMeasurements(38, 45, 43);
weatherData.setMeasurements(45.7f, 56.2f, 43);
weatherData.setMeasurements(38.3f, 45.7f, 43.4f);
}
}
|