设计模式之观察者模式

观察者模式(Observer)

定义

定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都可以得到通知并自动更新。

使用场景

主要角色

  1. Subject(主题)
  2. ConcreteSubject(具体主题)
  3. Observer(观察者)
  4. ConcreteObserver(具体观察者)

类图

示例代码

java 复制代码
public interface Subject {
    void addObserver(Observer observer);

    void removeObserver(Observer observer);

    void notifyObservers();
}
java 复制代码
public class WeatherStation implements Subject {
    private List<Observer> observers = new ArrayList<>();
    private String temperature;
    private String condition;

    public void setWeatherData(String temperature, String condition) {
        this.temperature = temperature;
        this.condition = condition;
        notifyObservers();
    }

    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }

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

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.update(temperature, condition);
        }
    }
}
java 复制代码
public interface Observer {
    void update(String temperature, String condition);
}
java 复制代码
public class TemperatureDisplay implements Observer {
    @Override
    public void update(String temperature, String condition) {
        System.out.println("Temperature Display: Current Temperature is " + temperature);
    }
}
java 复制代码
public class WeatherConditionDisplay implements Observer {
    @Override
    public void update(String temperature, String condition) {
        System.out.println("Weather Condition Display: Current Weather Condition is " + condition);
    }
}
java 复制代码
public class Client {
    public static void main(String[] args) {
        // 创建主题
        WeatherStation weatherStation = new WeatherStation();

        // 创建观察者
        Observer temperatureDisplay = new TemperatureDisplay();
        Observer weatherConditionDisplay = new WeatherConditionDisplay();

        // 注册观察者
        weatherStation.addObserver(temperatureDisplay);
        weatherStation.addObserver(weatherConditionDisplay);

        // 模拟天气数据更新
        weatherStation.setWeatherData("25°C", "Sunny");
    }
}
复制代码
Temperature Display: Current Temperature is 25°C
Weather Condition Display: Current Weather Condition is Sunny
相关推荐
日和雫5 小时前
面向对象与面向过程,谁才是“银弹”?
设计模式
geovindu11 小时前
rust: Iterator Pattern
开发语言·后端·设计模式·rust·行为模式·迭代器模
高晶1 天前
ARM 嵌入式 Linux 系统启动流程实战指南
设计模式·程序员
高晶1 天前
BMS 通信开发实战:从 PMBus 协议到数据采集的完整指南
设计模式·程序员
geovindu1 天前
rust:Memento Pattern(续)
开发语言·后端·设计模式·rust·行为模式·备忘录模
电子IT笔记1 天前
老MES登录改造:弱密码和暴破一起治
设计模式
牧瀬クリスだ1 天前
单例模式终极指南:从入门到防破坏
单例模式·设计模式
博风1 天前
9、设计模式应用举例:责任链模式:计算阶乘
设计模式·责任链模式
电子IT笔记1 天前
人走了,记录不能“空白”: MES×HR 离职人员下拉回显实战
设计模式
博风2 天前
8、设计模式应用举例:适配器模式:Iterator接口与Enumeration接口
设计模式·适配器模式