观察者模式:定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,他的所有依赖者都会受到通知并自动更新。
具体内容见:Head First设计模式
气象站模型:气象站提供气象数据,布告板显示。
具体内容见:Head First设计模式
气象站模型:气象站提供气象数据,布告板显示。
定义观察者接口
public interface Observer {
public void update(float temp,float humi,float pressure);
}
定义主题接口
public interface Subject {
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}
定义显示装置接口
public interface DisplayElement {
public void display();
}
具体主题
public class WeatherData implements Subject {
private ArrayList<Observer> observers;
private float temperature;
private float humidity;
private float pressure;
/**
*
*/
public WeatherData() {
observers = new ArrayList<Observer>();
}
/*
* (non-Javadoc)
*
* @see com.zen.dp.observer.Subject#notifyObservers()
*/
@Override
public void notifyObservers() {
for (Observer o : observers) {
o.update(temperature, humidity, pressure);
}
}
/*
* (non-Javadoc)
*
* @see
* com.zen.dp.observer.Subject#registerObserver(com.zen.dp.observer.Observer
* )
*/
@Override
public void registerObserver(Observer o) {
observers.add(o);
}
/*
* (non-Javadoc)
*
* @see
* com.zen.dp.observer.Subject#removeObserver(com.zen.dp.observer.Observer)
*/
@Override
public void removeObserver(Observer o) {
int i = observers.indexOf(o);
if (i >= 0)
observers.remove(i);
}
public void setMeasurements(float temp, float humi, float pressure) {
this.temperature = temp;
this.humidity = humi;
this.pressure = pressure;
notifyObservers();
}
}
具体观察者及显示装置
public class TVDisplay implements Observer, DisplayElement {
private float temperature;
private float humidity;
private Subject weatherData;
/**
*
*/
public TVDisplay(Subject wd) {
this.weatherData = wd;
wd.registerObserver(this);
}
/* (non-Javadoc)
* @see com.zen.dp.observer.Observer#update(float, float, float)
*/
@Override
public void update(float temp, float humi, float pressure) {
this.temperature=temp;
this.humidity=humi;
display();
}
/* (non-Javadoc)
* @see com.zen.dp.observer.DisplayElement#display()
*/
@Override
public void display() {
System.out.println("当前的气象条件是:温度为"+temperature+"摄氏度,湿度为"+humidity+"%");
}
}
气象站
public class WeatherStation {
public static void main(String[] args) {
WeatherData wd = new WeatherData();
TVDisplay tvdisplay = new TVDisplay(wd);
wd.setMeasurements(18, 46, 30);
wd.setMeasurements(20, 30, 28);
}
}