设计模式之观察者模式

观察者模式(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
相关推荐
ximu_polaris12 小时前
设计模式(C++)-行为型模式-模版方法模式
c++·设计模式
A-Jie-Y12 小时前
JAVA设计模式-抽象工厂模式
java·设计模式
故事还在继续吗13 小时前
设计模式完全指南
设计模式
薛定谔的悦14 小时前
共享数据总线(DPR)设计模式——嵌入式系统的“内存数据库”
jvm·数据库·设计模式
A-Jie-Y15 小时前
JAVA设计模式-建造者模式
java·设计模式
无敌秋16 小时前
# C++ 工厂方法模式实战指南
开发语言·c++·设计模式
a里啊里啊17 小时前
软考-软件评测师:知识点整理(七)——软件工程
设计模式·软件工程·软考·uml·结构化开发·软件评测师·软件模型
ximu_polaris18 小时前
设计模式(C++)-行为型模式-策略模式
c++·设计模式·策略模式
heimeiyingwang18 小时前
【架构实战】观察者模式在分布式系统中的应用
观察者模式·架构·wpf
geovindu19 小时前
go: Observer Pattern
开发语言·观察者模式·设计模式·golang