应对的情况:当一个可观察者的状态发生改变时,观察者的数据也要实时更新。
你可能第一时间会想到的是,直接在可观察者类上调用观察者的方法就行了。是的,这是一种最直接,也是最简单的方法。但这样做就使得可观察者和观察者的耦合性很高,且不能动态更改观察者的数量。
我们或许可以这样做,写一个可观察者的接口:
public interface Subject { public void registerObserver(Observer o);//注册观察者 public void removeObserver(Observer o);//移除观察者 public void notifyObservers();//通知观察者,其实就是调用观察者的方法 }
public interface Observer { public void update(float temp, float humidity, float pressure);//统一调用的方法 }
import java.util.*; public class WeatherData implements Subject { private ArrayList observers; private float temperature; private float humidity; private float pressure; public WeatherData() { observers = new ArrayList(); } 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(temperature, humidity, pressure);/*通过循环,调用组合在自己身上的观察者的统一方法,从而实现观察者的数据更新*/ } } public void measurementsChanged() {//可观察者状态发生改变后调用的方法 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; } }
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);/*通过实例化观察者时就可以注册了,也可以不用这样注册,像swing的监听器那样,如:button.addActionListener(new 观察者接口)*/ } public void update(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; display(); } public void display() { System.out.println("Current conditions: " + temperature + "F degrees and " + humidity + "% humidity"); } }
import java.util.*; 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, 29.2f); weatherData.setMeasurements(78, 90, 29.2f); } }
java.util.Observable; java.util.Observer;
原文地址:http://blog.csdn.net/u012367513/article/details/25044529