首頁常見問題正文

在Java中,什么叫觀察者設(shè)計(jì)模式(observer design pattern)?

更新時(shí)間:2023-04-25 來源:黑馬程序員 瀏覽量:

IT培訓(xùn)班

  觀察者設(shè)計(jì)模式是Java中的一種行為型設(shè)計(jì)模式,用于在對(duì)象間建立一種一對(duì)多的依賴關(guān)系,當(dāng)一個(gè)對(duì)象的狀態(tài)發(fā)生變化時(shí),它的所有依賴者都會(huì)得到通知并自動(dòng)更新。

  在觀察者設(shè)計(jì)模式中,有兩種角色:觀察者和被觀察者。被觀察者是一個(gè)主題或者一個(gè)事件源,它維護(hù)一組觀察者,并在狀態(tài)發(fā)生改變時(shí)通知它們。觀察者是依賴于被觀察者的對(duì)象,它們注冊(cè)自己到被觀察者,以便在狀態(tài)發(fā)生改變時(shí)能夠接收到通知并進(jìn)行相應(yīng)的處理。

import java.util.*;

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

class WeatherData {
    private ArrayList<Observer> 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 (Observer o : observers) {
            o.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();
    }
}

class CurrentConditionsDisplay implements Observer {
    private float temperature;
    private float humidity;
    
    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");
    }
}

class StatisticsDisplay implements Observer {
    private float temperatureSum = 0.0f;
    private float temperatureMin = Float.MAX_VALUE;
    private float temperatureMax = Float.MIN_VALUE;
    private int numReadings;
    
    public void update(float temperature, float humidity, float pressure) {
        temperatureSum += temperature;
        numReadings++;
        if (temperature < temperatureMin) {
            temperatureMin = temperature;
        }
        if (temperature > temperatureMax) {
            temperatureMax = temperature;
        }
        display();
    }
    
    public void display() {
        System.out.println("Avg/Max/Min temperature = "
            + (temperatureSum / numReadings) + "/"
            + temperatureMax + "/" + temperatureMin);
    }
}

public class WeatherStation {
    public static void main(String[] args) {
        WeatherData weatherData = new WeatherData();
        
        CurrentConditionsDisplay currentDisplay = new CurrentConditionsDisplay();
        StatisticsDisplay statisticsDisplay = new StatisticsDisplay();
        
        weatherData.registerObserver(currentDisplay);
        weatherData.registerObserver(statisticsDisplay);
        
        weatherData.setMeasurements(80, 65, 30.4f);
        weatherData.setMeasurements(82, 70, 29.2f);
        weatherData.setMeasurements(78, 90, 29.2f);
    }
}

  Java中的觀察者設(shè)計(jì)模式是通過使用接口和抽象類來實(shí)現(xiàn)的。被觀察者通常實(shí)現(xiàn)一個(gè)名為“Observable”的抽象類,而觀察者則實(shí)現(xiàn)一個(gè)名為“Observer”的接口。被觀察者在狀態(tài)發(fā)生改變時(shí),調(diào)用其“notifyObservers()”方法來通知所有觀察者,而觀察者則實(shí)現(xiàn)“update()”方法來接收并處理通知。

  下面是一個(gè)簡(jiǎn)單的Java代碼演示觀察者設(shè)計(jì)模式,其中一個(gè)WeatherData類是被觀察者,而兩個(gè)觀察者CurrentConditionsDisplay和StatisticsDisplay都實(shí)現(xiàn)了Observer接口,以便接收WeatherData對(duì)象的狀態(tài)變化通知并作出相應(yīng)的處理。

  輸出結(jié)果為:

Current conditions: 80.0F degrees and 65.0% humidity
Avg/Max/Min temperature = 80.0/80.0/80.0
Current conditions: 82.0F degrees and 70.0% humidity
Avg/Max/Min temperature = 81.0/82.0/80.0
Current conditions: 78.0F degrees and 90.0% humidity
Avg/Max/Min temperature = 80.0/82.0/78

  以上代碼演示了一個(gè)氣象站的場(chǎng)景,其中WeatherData類是被觀察者,它維護(hù)了一個(gè)觀察者列表observers,并提供了registerObserver、removeObserver、notifyObservers、measurementsChanged和setMeasurements等方法。

  在主函數(shù)中,創(chuàng)建了兩個(gè)觀察者對(duì)象currentDisplay和statisticsDisplay,并將它們注冊(cè)到WeatherData對(duì)象weatherData的觀察者列表中。接著調(diào)用setMeasurements方法更新氣象數(shù)據(jù),并觀察觀察者對(duì)象的相應(yīng)輸出。

  CurrentConditionsDisplay類是一個(gè)觀察者,它實(shí)現(xiàn)了Observer接口,并在update方法中接收到WeatherData對(duì)象的狀態(tài)變化通知。在這個(gè)例子中,CurrentConditionsDisplay類只是簡(jiǎn)單地輸出了當(dāng)前的溫度和濕度。

  StatisticsDisplay類也是一個(gè)觀察者,它在update方法中累加溫度數(shù)據(jù),并計(jì)算平均值、最大值和最小值,并在display方法中輸出。

  這個(gè)例子演示了觀察者設(shè)計(jì)模式的基本思想:被觀察者維護(hù)一個(gè)觀察者列表,觀察者在被觀察者狀態(tài)變化時(shí)接收通知并作出相應(yīng)的處理。在實(shí)際應(yīng)用中,觀察者設(shè)計(jì)模式可以用于實(shí)現(xiàn)事件驅(qū)動(dòng)系統(tǒng)、GUI程序開發(fā)、消息隊(duì)列、通知系統(tǒng)等場(chǎng)景。

  觀察者設(shè)計(jì)模式常用于GUI程序開發(fā)、事件驅(qū)動(dòng)系統(tǒng)、通知系統(tǒng)等場(chǎng)景。它可以幫助程序員實(shí)現(xiàn)松耦合、高內(nèi)聚的設(shè)計(jì),提高系統(tǒng)的可維護(hù)性和可擴(kuò)展性。

分享到:
在線咨詢 我要報(bào)名
和我們?cè)诰€交談!