behavior:观察者模式(Observable)

2019-03-20  本文已影响0人  柳源居士

通俗易懂的理解:
出版社+读者=观察者模式
它有以下几个含义:

在实现的时候,我们把各自角色重新命名:
出版社 = 主题(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;
    }

}
上一篇下一篇

猜你喜欢

热点阅读