设计模式:观察者模式示例

让我们通过一个天气监测应用的例子来展示观察者模式。在这个应用中,WeatherStation 作为可观察的主题,它会跟踪天气数据的变化。Display 作为观察者,当天气数据更新时会显示最新的信息。

示例代码:

java 复制代码
import java.util.ArrayList;
import java.util.List;

// 观察者接口
interface Observer {
    void update(float temperature, float humidity, float pressure);
}

// 可观察对象接口
interface Observable {
    void registerObserver(Observer o);
    void removeObserver(Observer o);
    void notifyObservers();
}

// 具体可观察对象:WeatherStation
class WeatherStation implements Observable {
    private List<Observer> observers;
    private float temperature;
    private float humidity;
    private float pressure;

    public WeatherStation() {
        observers = new ArrayList<>();
    }

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

    public void measurementsChanged() {
        notifyObservers();
    }

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

    @Override
    public void removeObserver(Observer o) {
        observers.remove(o);
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(temperature, humidity, pressure);
        }
    }
}

// 具体观察者:Display
class Display implements Observer {
    private Observable weatherStation;

    public Display(Observable weatherStation) {
        this.weatherStation = weatherStation;
        weatherStation.registerObserver(this);
    }

    @Override
    public void update(float temperature, float humidity, float pressure) {
        System.out.println("Current conditions: " + temperature + "C degrees and " + humidity + "% humidity");
    }

    public void unsubscribe() {
        weatherStation.removeObserver(this);
    }
}

// 客户端代码
public class ObserverPatternExample {
    public static void main(String[] args) {
        WeatherStation weatherStation = new WeatherStation();
        Display currentDisplay = new Display(weatherStation);

        // 模拟新的天气测量数据
        weatherStation.setMeasurements(28.2f, 65f, 1013.1f);
        weatherStation.setMeasurements(22.1f, 70f, 1012.5f);

        // 当不再需要显示当前天气情况时,取消订阅
        currentDisplay.unsubscribe();

        // 即使更新了天气数据,Display 也不会收到通知
        weatherStation.setMeasurements(25.5f, 60f, 1014.9f);
    }
}

在这个例子中,WeatherStation 类实现了 Observable 接口,负责管理观察者并在数据更新时通知它们。Display 类实现了 Observer 接口,并在接收到更新通知时显示当前的天气条件。客户端代码创建了一个天气站对象和一个显示器对象,并模拟了天气数据的变化。

这个例子展示了观察者模式的核心概念:对象可以订阅和取消订阅事件,而主题对象在状态变化时会通知所有的订阅者。

总结

这个天气监测应用的例子展示了观察者模式在实际应用中的使用。该模式允许对象在无需知道其他对象具体实现的情况下相互通信,从而实现了主题和观察者之间的解耦。通过使用观察者模式,我们可以轻松地添加新的观察者,或者在不影响其他观察者的情况下更改主题的状态更新逻辑。

相关推荐
wy_hhxx9 小时前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
AAA修煤气灶刘哥9 小时前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
用户624293196621 天前
告别 Electron 臃肿与 Wireshark 老化界面:用 Rust + Tauri 2.0 构建多总线网络与现场总线深度分析仪 Omni-Probe
设计模式
是2的10次方啊1 天前
设计模式与生活㉒:暖气热不热,得一间一间摸过去
设计模式
bigbread2 天前
迭代器模式-在区域健康档案导出中的实战应用
设计模式
装不满的克莱因瓶2 天前
设计模式之策略模式核心概念和应用场景
java·后端·设计模式·架构·系统架构·策略模式
是2的10次方啊2 天前
设计模式与生活㉑:一句“建议复查”,是好几句话拼出来的
设计模式
杯子不吃紫菜4 天前
LangGraph 体系实战(下):中断恢复、流式、子图与设计模式
单片机·嵌入式硬件·设计模式
是2的10次方啊4 天前
设计模式与生活⑳:楼里的事都找前台,你就再没见过师傅
设计模式
是2的10次方啊5 天前
设计模式与生活⑲:投影连不上,别急着换投影仪
设计模式