观察者模式: 定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,他的所有依赖者都会受到通知并自动更新。
1,定义事件源接口
package com.pattern.observer; public interface Subject { public void registerObserver(Observer o); public void removeObserver(Observer o); public void notifyObserver(); }
2,定义事件源
package com.pattern.observer; import java.util.ArrayList; /** * 事件源 */ public class WeatherData implements Subject { private ArrayList observers; private float temperature; private float humidity; private float pressure; public WeatherData() { observers = new ArrayList(); } /** * @see com.pattern.observer.Subject#registerObserver(com.pattern.observer.Observer) */ @Override public void registerObserver(Observer o) { observers.add(o); } /** * @see com.pattern.observer.Subject#removeObserver(com.pattern.observer.Observer) */ @Override public void removeObserver(Observer o) { int i = observers.indexOf(o); if (i >= 0) { observers.remove(i); } } /** * @see com.pattern.observer.Subject#notifyObserver() */ @Override public void notifyObserver() { for(int i=0;i<observers.size();i++){ Observer observer = (Observer)observers.get(i); observer.update(temperature, humidity, pressure); } } public void measurementsChanged(){ notifyObserver(); } public void setMeasurements(float temperature,float humidity,float pressure){ this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; measurementsChanged(); } }
3,定义观察者接口
package com.pattern.observer; public interface Observer { public void update(float temp,float humidity,float pressure); }
4,定义显示接口
package com.pattern.observer; public interface DisplayElement { public void display(); }
5,观察者实现类
package com.pattern.observer; 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); } /** * @see com.pattern.observer.DisplayElement#display() */ @Override public void display() { System.out.println("Current conditions: "+temperature +"F degrees and "+humidity+"% humidity"); } /** * @see com.pattern.observer.Observer#update(float, float, float) */ @Override public void update(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; display(); } }
6,测试
package com.pattern.observer; public class WeatherStation { public static void main(String[] args){ WeatherData weatherData = new WeatherData(); CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData); weatherData.setMeasurements(80, 65, 30.4f); } }
类图如下所示: