Head First 设计模式学习系列(二) 观察者模式

观察者模式定义了一系列对象之间的一对多关系,当一个对象(主题,也称被观察者)改变状态,其他依赖者(观察者)都会收到通知.

1.实例描述

现有负责追踪天气状况(温度,湿度,气压)的WeatherData对象,利用该对象建立一个气象观测站应用,有三种布告板,分别显示目前的状况,气象统计及简单的预报,当WeatherData里面有最新的数据测量时,三种布告板必段实时更新。并要求我们能灵活的增加观察者,移除观察者。同时在布告板的块数可能增加,如增加酷热指数布告板。

2.分析思路

根据定义和描述,我们可以将WeatherDate作为主题,三块布告板作为观察者。首先创建Subjec接口,里面定义添加,移除,通知观察者功能,实现该接口的WeatherData通过ArrayList字段来模拟所有观察者,还有温度,湿度,气压字段,实现接口的方法。然后创建Observer接口,定义更新功能,由于每个布告板还有不同的展示方式,我们还需创建一个DispayElement接口,里面定义展示行为。所有的布告板都实现了Observer和DispayElement接口,并且定义了私有的Subject和相关私有字段。
WeatherData里面实现了注册和移除观察者的方法。当要增加一个布告板时,我们只需要实现Observer,DisplayElement两个接口,并且注册。

3.类图实现

主题:

Head First 设计模式学习系列(二) 观察者模式_第1张图片

观察者:

Head First 设计模式学习系列(二) 观察者模式_第2张图片

4.代码实现

Subject:主题接口

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

WeatherData:主题的具体实现

import java.util.*;

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(o);
    }
    
    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 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();
    }
    
    // other WeatherData methods here
    
    public float getTemperature() {
        return temperature;
    }
    
    public float getHumidity() {
        return humidity;
    }
    
    public float getPressure() {
        return pressure;
    }
}

Observer:观察者核心接口

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

** DisplayElement:**布告板展示行为的接口

public interface DisplayElement {
    public void display();
}

CurrentConditionsDisplay:观察者1,即提供目前状况的布告板

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() {
        System.out.println("Current conditions: " + temperature 
            + "F degrees and " + humidity + "% humidity");
    }
}

StatisticsDisplay:观察者2,即提供气象统计的布告板

public class StatisticsDisplay implements Observer, DisplayElement {
    private float maxTemp = 0.0f;
    private float minTemp = 200;
    private float tempSum = 0.0f;
    private int numReadings;
    private Subject weatherData;

    public StatisticsDisplay(WeatherData weatherData) {
        this.weatherData = weatherData;
        weatherData.registerObserver(this);
    }

    public void update(float temp, float humidity, float pressure) {
        tempSum += temp;
        numReadings++;

        if (temp > maxTemp) {
            maxTemp = temp;
        }

        if (temp < minTemp) {
            minTemp = temp;
        }

        display();
    }

    public void display() {
        System.out.println("Avg/Max/Min temperature = "
                + (tempSum / numReadings) + "/" + maxTemp + "/" + minTemp);
    }
}

**ForecastDisplay: **观察者3,即提供简单预报功能的布告板

public class ForecastDisplay implements Observer, DisplayElement {
    private float currentPressure = 29.92f;
    private float lastPressure;
    private Subject weatherData;

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

    public void update(float temp, float humidity, float pressure) {
        lastPressure = currentPressure;
        currentPressure = pressure;

        display();
    }

    public void display() {
        System.out.print("Forecast: ");
        if (currentPressure > lastPressure) {
            System.out.println("Improving weather on the way!");
        } else if (currentPressure == lastPressure) {
            System.out.println("More of the same");
        } else if (currentPressure < lastPressure) {
            System.out.println("Watch out for cooler, rainy weather");
        }
    }
}

HeatIndexDisplay:观察者4,即新增加的提供酷热指数的布告板

public class HeatIndexDisplay implements Observer, DisplayElement {
    float heatIndex = 0.0f;
    private Subject weatherData;

    public HeatIndexDisplay(WeatherData weatherData) {
        this.weatherData = weatherData;
        weatherData.registerObserver(this);
    }

    public void update(float t, float rh, float pressure) {
        heatIndex = computeHeatIndex(t, rh);
        display();
    }

    private float computeHeatIndex(float t, float rh) {
        float index = (float) ((16.923 + (0.185212 * t) + (5.37941 * rh)
                - (0.100254 * t * rh) + (0.00941695 * (t * t))
                + (0.00728898 * (rh * rh)) + (0.000345372 * (t * t * rh))
                - (0.000814971 * (t * rh * rh))
                + (0.0000102102 * (t * t * rh * rh))
                - (0.000038646 * (t * t * t)) + (0.0000291583 * (rh * rh * rh))
                + (0.00000142721 * (t * t * t * rh))
                + (0.000000197483 * (t * rh * rh * rh))
                - (0.0000000218429 * (t * t * t * rh * rh)) + 0.000000000843296 * (t
                * t * rh * rh * rh)) - (0.0000000000481975 * (t * t * t * rh
                * rh * rh)));
        return index;
    }

    public void display() {
        System.out.println("Heat index is " + heatIndex);
    }
}

你可能感兴趣的:(Head First 设计模式学习系列(二) 观察者模式)