美文网首页
观察者模式

观察者模式

作者: 阳光的技术小栈 | 来源:发表于2018-01-22 15:12 被阅读14次

观察者模式定义了对象之间的一对多依赖,这样一来,当一个对象改变状态时,它的所有依赖都会收到通知并自动更新。

示例—气象观测站的监测系统

已有一个WeatherData对象,负责追踪目前的天气状况(温度、湿度、欺压)。建立一个应用, 有三种布告板,分别显示目前的状况、气象统计及简单的预报。当WeatherData对象获得最新的测量数据时,三种布告板必须实时更新。而且可以扩展,公布一组api,可让其他开发人员写出自己的气象布告板,并插入此应用。

有两种方式实现:自定义观察者和内置观察类

自定义观察者

  • UML图表示
气象站三种布告板的设计-自定义观察者
  • 代码演示
import java.util.ArrayList;
import java.util.List;

interface Subject{
    void registerObserver(Observer o);
    void removeObserver(Observer o);
    void notifyObservers();
}

class WeatherData implements Subject{

    private ArrayList observers;
    private float temperature;
    private float humidity;
    private float pressure;

    public WeatherData(){
        observers = new ArrayList();
    }

    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        int i = observers.indexOf(o);
        if (i >= 0) {
            observers.remove(i);
        }
    }

    @Override
    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();
    }
}

interface Observer{
    void update(float temp, float humidity, float pressure);
}

interface DisplayElement{
    void display();
}

class CurrentConditionsDisplay implements Observer,DisplayElement{

    private float temperature;
    private float humidity;
    private Subject weatherData;

    public CurrentConditionsDisplay(Subject weatherData){
        this.weatherData = weatherData;
        weatherData.registerObserver(this);
    }

    @Override
    public void update(float temp, float humidity, float pressure) {
        this.temperature = temp;
        this.humidity = humidity;
        display();
    }

    @Override
    public void display() {
        System.out.println("Current conditions: " + temperature
        + "F degrees and " + humidity + "% humidity" );
    }
}

class StatisticsDisplay implements Observer, DisplayElement{

    private List<Float> temperatureList;
    private List<Float> humidityList;
    private List<Float> pressureList;

    private Subject weatherData;

    public StatisticsDisplay(Subject weatherData){
        this.weatherData = weatherData;
        temperatureList = new ArrayList<Float>();
        humidityList = new ArrayList<Float>();
        pressureList = new ArrayList<Float>();
        weatherData.registerObserver(this);
    }

    @Override
    public void update(float temp, float humidity, float pressure) {
        temperatureList.add(temp);
        humidityList.add(humidity);
        pressureList.add(pressure);
        display();
    }

    @Override
    public void display() {
        System.out.println("Statistics Average Data: " + calAverage(temperatureList)
                + "F degrees and " + calAverage(humidityList) + "% humidity and average pressure is "
                + calAverage(pressureList));
    }

    private Float calAverage(List<Float> list){
        Float sum = 0.0f;
        for (Float item : list){
            sum += item;
        }
        return sum / (float) list.size();
    }
}

class ForecastDisplay implements Observer, DisplayElement{

    private float temperature;
    private float humidity;
    private float pressure;

    private Subject weatherData;

    public ForecastDisplay(Subject weatherData){
        this.weatherData = weatherData;
        weatherData.registerObserver(this);
    }


    @Override
    public void update(float temp, float humidity, float pressure) {
        this.temperature = temp + (float) 1;
        this.humidity = humidity - (float) 1;
        this.pressure = pressure +  0.5f;
        display();
    }

    @Override
    public void display() {
        System.out.println("Forecast conditions: " + temperature
                + "F degrees and " + humidity + "% humidity and pressure is "
                + pressure);
    }
}

public class WeatherStation{
    public static void main(String[] args) {
        WeatherData weatherData = new WeatherData();

        CurrentConditionsDisplay currentConditionsDisplay = 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);

    }
}
  • 测试结果
Current conditions: 80.0F degrees and 65.0% humidity
Statistics Average Data: 80.0F degrees and 65.0% humidity and average pressure is 30.4
Forecast conditions: 81.0F degrees and 64.0% humidity and pressure is 30.9
Current conditions: 82.0F degrees and 70.0% humidity
Statistics Average Data: 81.0F degrees and 67.5% humidity and average pressure is 29.8
Forecast conditions: 83.0F degrees and 69.0% humidity and pressure is 29.7
Current conditions: 78.0F degrees and 90.0% humidity
Statistics Average Data: 80.0F degrees and 75.0% humidity and average pressure is 29.6
Forecast conditions: 79.0F degrees and 89.0% humidity and pressure is 29.7

内置观察类

  • UML图表示
气象站三种布告板的设计-内置观察类
  • 代码演示
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

class WeatherData2 extends Observable{
    private float temperature;
    private float humidity;
    private float pressure;

    public void measurementsChanged(){
        setChanged();
        notifyObservers();
    }

    public void setMeasurements(float temperature, float humidity, float pressure){
        this.temperature = temperature;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }

    float getTemperature() {
        return temperature;
    }

    float getHumidity() {
        return humidity;
    }

    float getPressure(){
        return pressure;
    }

}

class CurrentConditionsDisplay2 implements Observer,DisplayElement{

    private float temperature;
    private float humidity;
    private Observable observable;

    public CurrentConditionsDisplay2(Observable observable){
        this.observable = observable;
        observable.addObserver(this);
    }

    @Override
    public void display() {
        System.out.println("Current conditions: " + temperature
                + "F degrees and " + humidity + "% humidity" );
    }

    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof WeatherData2){
            WeatherData2 weatherData2 = (WeatherData2) o;
            this.temperature = weatherData2.getTemperature();
            this.humidity = weatherData2.getHumidity();
            display();
        }
    }
}

class StatisticsDisplay2 implements Observer, DisplayElement{

    private Observable observable;
    private List<Float> temperatureList;
    private List<Float> humidityList;
    private List<Float> pressureList;

    public StatisticsDisplay2(Observable observable){
        this.observable = observable;
        temperatureList = new ArrayList<Float>();
        humidityList = new ArrayList<Float>();
        pressureList = new ArrayList<Float>();
        observable.addObserver(this);
    }

    @Override
    public void display() {
        System.out.println("Statistics Average Data: " + calAverage(temperatureList)
                + "F degrees and " + calAverage(humidityList) + "% humidity and average pressure is "
                + calAverage(pressureList));
    }

    private Float calAverage(List<Float> list){
        Float sum = 0.0f;
        for (Float item : list){
            sum += item;
        }
        return sum / (float) list.size();
    }

    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof WeatherData2){
            WeatherData2 weatherData2 = (WeatherData2) o;
            temperatureList.add(weatherData2.getTemperature());
            humidityList.add(weatherData2.getHumidity());
            pressureList.add(weatherData2.getPressure());
            display();
        }
    }
}

class ForecastDisplay2 implements Observer, DisplayElement{

    private float temperature;
    private float humidity;
    private float pressure;

    private Observable observable;

    public ForecastDisplay2(Observable observable){
        this.observable = observable;
        observable.addObserver(this);
    }

    @Override
    public void display() {
        System.out.println("Forecast conditions: " + temperature
                + "F degrees and " + humidity + "% humidity and pressure is "
                + pressure);
    }

    @Override
    public void update(Observable o, Object arg) {
        if (o instanceof WeatherData2){
            WeatherData2 weatherData2 = (WeatherData2) o;
            this.temperature = weatherData2.getTemperature() + (float) 1;
            this.humidity = weatherData2.getHumidity() - (float) 1;
            this.pressure = weatherData2.getPressure() +  0.5f;
            display();
        }
    }
}

public class WeatherStation2 {
    public static void main(String[] args) {
        WeatherData2 weatherData2 = new WeatherData2();

        CurrentConditionsDisplay2 currentConditionsDisplay = new CurrentConditionsDisplay2(weatherData2);
        StatisticsDisplay2 statisticsDisplay = new StatisticsDisplay2(weatherData2);
        ForecastDisplay2 forecastDisplay = new ForecastDisplay2(weatherData2);


        weatherData2.setMeasurements(80,65,30.4f);
        weatherData2.setMeasurements(82,70,29.2f);
        weatherData2.setMeasurements(78,90,29.2f);

    }
}
  • 测试结果
Forecast conditions: 81.0F degrees and 64.0% humidity and pressure is 30.9
Statistics Average Data: 80.0F degrees and 65.0% humidity and average pressure is 30.4
Current conditions: 80.0F degrees and 65.0% humidity
Forecast conditions: 83.0F degrees and 69.0% humidity and pressure is 29.7
Statistics Average Data: 81.0F degrees and 67.5% humidity and average pressure is 29.8
Current conditions: 82.0F degrees and 70.0% humidity
Forecast conditions: 79.0F degrees and 89.0% humidity and pressure is 29.7
Statistics Average Data: 80.0F degrees and 75.0% humidity and average pressure is 29.6
Current conditions: 78.0F degrees and 90.0% humidity

结论

两种方式都可以实现观察者模式,各有特色。两种模式都能实现“推”和“拉”的方式。

  • 自定义观察者:可以实现用接口开发,而不是实现开发,实现方式比较自由,但需要自定义的代码多。
  • 内置观察类:不能实现接口开发,必须用继承的方式开发,但不需要自己实现注册、取消等代码。

相关文章

  • 11.9设计模式-观察者模式-详解

    设计模式-观察者模式 观察者模式详解 观察者模式在android中的实际运用 1.观察者模式详解 2.观察者模式在...

  • RxJava基础—观察者模式

    设计模式-观察者模式 观察者模式:观察者模式(有时又被称为发布(publish )-订阅(Subscribe)模式...

  • 前端面试考点之手写系列

    1、观察者模式 观察者模式(基于发布订阅模式) 有观察者,也有被观察者。 观察者需要放到被观察者列表中,被观察者的...

  • RxJava 原理篇

    一、框架思想 观察者模式观察者自下而上注入被观察者被观察者自上而下发射事件观察者模式 装饰器模式自上而下,被观察者...

  • 观察者模式

    观察者模式概念 观察者模式是对象的行为模式,又叫作发布-订阅(publish/subscrible)模式。 观察者...

  • 设计模式-观察者模式

    观察者模式介绍 观察者模式定义 观察者模式(又被称为发布-订阅(Publish/Subscribe)模式,属于行为...

  • 观察者模式

    观察者模式 观察者模式的定义 观察者模式(Observer Pattern)也叫做发布订阅模式(Publish/s...

  • iOS设计模式之观察者模式

    观察者模式 1、什么是观察者模式 观察者模式有时又被称为发布(publish)-订阅(Subscribe)模式、模...

  • 观察者模式和发布订阅模式区别

    观察者模式 所谓观察者模式,其实就是为了实现松耦合(loosely coupled)。 在观察者模式中,观察者需要...

  • RxJava(二)

    一、观察者模式 1.1、传统的观察者模式 1.2、RxJava 的观察者模式 区别传统的观察者模式是一个 Obse...

网友评论

      本文标题:观察者模式

      本文链接:https://www.haomeiwen.com/subject/hkhrixtx.html