设计模式之观察者模式

观察者模式(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
相关推荐
五点六六六4 小时前
基于 AST 与 Proxy沙箱 的局部代码热验证
前端·设计模式·架构
wwdoffice011018 小时前
304和316不锈钢有什么区别?哪个更好?
设计模式
网小鱼的学习笔记19 小时前
创建型设计模式(工厂、builder、原型、单例)
java·后端·设计模式
逆境不可逃19 小时前
【从零入门23种设计模式21】行为型之空对象模式
java·开发语言·数据库·算法·设计模式·职场和发展
蜜獾云1 天前
设计模式之命令模式:给其他模块下达命令
设计模式·命令模式
小湘西2 天前
拓扑排序(Topological Sort)
python·设计模式
蜜獾云2 天前
设计模式之观察者模式:监听目标对象的状态改变
观察者模式·设计模式·rxjava
知无不研2 天前
中介者模式
c++·设计模式·中介者模式
bmseven2 天前
大白话讲解23种设计模式简介
设计模式
蜜獾云2 天前
设计模式之代理模式:本地接口代理远程接口的调用
设计模式·系统安全·代理模式