package b_Observer.jdk;
import java.util.Observable;
import java.util.Observer;
interface DisplayElement {
void display();
}
public class CurrentConditionsDisplay implements Observer, DisplayElement {
private Observable observable;
private float humidity;
private float pressure;
// 将当前对象添加为观察者
public CurrentConditionsDisplay(Observable observable) {
this.observable = observable;
observable.addObserver(this);
}
public void update(Observable o, Object arg) {
if (o instanceof WeatherData) {
WeatherData weatherData = (WeatherData) o;
this.humidity = weatherData.getHumidity();
this.pressure = weatherData.getPressure();
display();
}
}
public void display() {
System.out.println(humidity + " " + pressure);
}
}
package b_Observer.jdk;
import java.util.Observable;
public class WeatherData extends Observable {
private float temperature;
private float humidity;
private float pressure;
public WeatherData() {
}
public void measurementsChanged() {
//notifyObservers()调用之前要先setChanged()表示数据已经改变
setChanged();
//使用此方法没有传送数据对象,表示采用的方式是'拉'
notifyObservers();
}
public void setMeasurements(float temperature, float humidity,
float pressure) {
this.temperature = temperature;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}
//数据采用拉的方式,所以需要提供get()
public float getTemperature() {
return temperature;
}
public float getHumidity() {
return humidity;
}
public float getPressure() {
return pressure;
}
}
package b_Observer.jdk;
/**
* observerable缺点
* 1:是类,无法将关键的地方保护起来,由于setChanged()为protected,所以必须继承采用使用此对象
* 违反第二原则,多用组合,少用继承
*
* PropertyChangeListener:javabean里面的观察者模式
*
*
*/
public class WeatherStation {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
//2个布告板(观察者)
CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(
weatherData);
weatherData.setMeasurements(80, 65, 10);
weatherData.setMeasurements(80, 62, 10);
}
}