通俗易懂的理解:
出版社+读者=观察者模式
它有以下几个含义:
- 出版社负责发行报纸
- 读者订阅报纸,当有新的报纸发行的时候,它一定会被送到读者手中
- 当读者不想看报纸的时候,只需要取消订阅就可以了
- 只要出版社存在,就一直会有读者订阅报纸
在实现的时候,我们把各自角色重新命名:
出版社 = 主题(Subject)| 被观察对象(Observable)
读者 = 观察者(Observer)
定义:
定义了对象之间的一对多依赖,这样,当一个对象改变状态时,它的所有依赖着都会收到通知并自动更新。
类图:
类图.png
简单实现:
package observable;
import java.util.Observable;
import java.util.Observer;
public class CurrentConditionsDisplay implements Observer,DisplayElement{
Observable observable;
private float temprature;
private float humidity;
public CurrentConditionsDisplay(Observable observable) {
this.observable = observable;
observable.addObserver(this);
}
@Override
public void update(Observable o, Object arg) {
if(o instanceof WeatherData){
WeatherData weatherData=(WeatherData)o;
this.temprature=weatherData.getTemperature();
this.humidity=weatherData.getHumidity();
display();
}
}
@Override
public void display() {
System.out.println("Current conditions: "+temprature + "F degress and "+humidity+"% humidity");
}
}
package observable;
public interface DisplayElement {
public void display();
}
package observable;
public class TestObservable {
public static void test(){
WeatherData weatherData=new WeatherData();
CurrentConditionsDisplay currentConditionsDisplay=new CurrentConditionsDisplay(weatherData);
//主题内容改变,通知观察者
weatherData.setMeasurements(81,82,80);
}
}
package observable;
import java.util.Observable;
public class WeatherData extends Observable {
private float temperature;
private float humidity;
private float pressure;
public WeatherData() {
}
public void measurementsChanged(){
setChanged();
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;
}
}
网友评论