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


类图

设计模式——观察者模式(Observer Pattern)_观察者模式

(图片源于网络)


代码实现(Java)

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


//WeatherData.java
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 float getTemperature() { 
        return temperature; 
    } 
    public float getHumidity() { 
        return humidity; 
    } 
    public float getPressure() { 
        return pressure; 
    }
    public void setMeasurements(float temperature, float humidity, float pressure) { 
        this.temperature = temperature; 
        this.humidity = humidity; 
        this.pressure = pressure; 
        measurementsChanged(); 
    }
    public void measurementsChanged() { 
        notifyObservers(); 
    }
}


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


//DisplayElement.java
public interface DisplayElement { 
        void display(); 
}


// CurrentConditionsDisplay.java
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");
    }
}


测试代码

// WeatherStation.java
public class WeatherStation {
    public static void main(String[] args) {
        WeatherData weatherData = new WeatherData();
        CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay(weatherData);
        weatherData.setMeasurements(80, 65, 30.4f);
    }
}


运行结果

设计模式——观察者模式(Observer Pattern)_设计模式_02