OO设计模式02—观测者模式(Observer )
OO设计模式—观测者模式(Observer )
问题的引出:
首先看看报纸和杂志的订阅是怎么回事:
1.报社的业务就是出版报纸。
2.像某家报社订阅报纸,只要他们有新报纸出版,就会给你送来。只要你是他们的订户,你就会一直收到报纸。
3.当你不想看报纸的时候,取消订阅,他们就不会再送新报纸来了。
4.只要报纸还在运营,就会一直有人(或单位)向他们订阅报纸或取消订阅报纸。
这就是个典型的观察者模式的例子。
出版者被定义为“主题(Subject)”,订阅者被定义为“观察者(Observer)”
观察者模式定义:定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,他的所有依赖者都会收到通知并自动更新。
设计原则tip1:为了交互对象之间的松耦合设计而努力。
松耦合设计之所以能让我们建立有弹性的OO系统,能够应对变化是因为对象之间的互相依赖降到最低。
一个气象站的例子:
public interface Subject{public void registerObserver(Observer o);//regist a new observerpublic void removeObserver(Observer o);public void notifyObserver();//when state is change use this method to notify all observer}public interface Observer{public void update(float temp,float humidity,float pressure);}public interface DisplayElement{public void display();}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}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 observeer = (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();}// other WeatherData() method}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);}public void update(float temperature, float humidity, float pressure){this.temperature = temperature;this.humidity = humidity;display();}public void display(){//add display method }}public class WeatherStation{public static void main(String[] args) {WeatherData weatherData = new WeatherData();CurrentConditionsDisplay currentDisplay =new CurrentConditionsDisplay(weatherData);weatherData.setMeasurements(80,65,30.4f);}}