1.定义
观察者模式在对象之间定义一对多的依赖,这样一来,当一个对象改变状态,依赖他的对象都会收到通知,并自动更新。
2. 案例分析
假设现有以气象系统,我们所需要完成的是当气象站数据更新时,同步更新我们的布告板(即显示装置)。
我们的需要利用WeatherData对象取得数据,并更新三个布告板:目前状况,气象统计,天气预报。
下面我们用类图定义观察者模式
3. 实现气象站
Subject接口类
package sxd.learn.dp;
public interface Subject{
public void registerObserver(Observer o);
public void removeObserver(Observer o);
public void notifyObservers();
}
Observer接口类
package sxd.learn.dp;
public interface Observer{
public void update(float temp, float humidity, float pressure);
}
DisplayElement接口类
package sxd.learn.dp;
public interface DisplayElement{
public void display();
}
用观察者模式实现WeatherData类
package sxd.learn.dp;
import java.util.ArrayList;
public class WeatherData implements Subject{
private ArrayList<Observer> observers;
private float temperture;
private float humidity;
private float pressure;
public WeatherData(){
observers = new ArrayList<Observer>();
}
public void registerObserver(Observer o){
observers.add(o);
}
public void removeObserver(Observer o){
int i = observers.indexOf(o);
if(i > 0){
observers.remove(i);
}
}
public void notifyObservers(){
for (int i = 0; i < observers.size() ; i++) {
Observer observer = (Observer) observers.get(i);
observer.update(temperture, humidity , pressure);
}
}
public void measurementsChanged(){
notifyObservers();
}
public void setMeasurements(float temperture, float humidity, float pressure){
this.temperture = temperture;
this.humidity = humidity;
this.pressure = pressure;
measurementsChanged();
}
}
布告板类CurrentConditionsDisplay
package sxd.learn.dp;
public class CurrentConditionsDisplay implements Observer, DisplayElement{
private float temperature;
private float humidity;
private Subject weatherData;
public CurrentConditionsDisplay(Subject weatherData){
this.weatherData = weatherData;
weatherData.registerObserver(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(float temp, float humidity, float pressure) {
// TODO Auto-generated method stub
this.temperature = temp;
this.humidity = humidity;
display();
}
}
测试程序类
package sxd.learn.dp;
public class WeatherStation {
public static void main(String[] args){
WeatherData weatherData = new WeatherData();
CurrentConditionsDisplay currentDisplay =
new CurrentConditionsDisplay(weatherData);
// StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData);
// ForecastDisplay forecastDisplay = new ForecastDisplay(weatherData);
weatherData.setMeasurements(80, 65, 30.4f);
weatherData.setMeasurements(82, 70, 30.3f);
weatherData.setMeasurements(78, 90, 29.2f);
}
}