设计模式之观察者模式

观察者模式(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
相关推荐
软考真题app5 小时前
软件设计师考试结构型设计模式考点全解析
设计模式·软件设计师·结构型设计模式·考试考点
xiaolin033310 小时前
【设计模式】- 行为型模式1
设计模式·状态模式·责任链模式·策略模式·命令模式·模板方法模式·行为型模式
沐土Arvin11 小时前
深入理解 requestIdleCallback:浏览器空闲时段的性能优化利器
开发语言·前端·javascript·设计模式·html
bao_lanlan12 小时前
兰亭妙微:用系统化思维重构智能座舱 UI 体验
ui·设计模式·信息可视化·人机交互·交互·ux·外观模式
总是难免13 小时前
设计模式 - 单例模式 - Tips
java·单例模式·设计模式
Java致死18 小时前
设计模式Java
java·开发语言·设计模式
ghost1431 天前
C#学习第23天:面向对象设计模式
开发语言·学习·设计模式·c#
敲代码的 蜡笔小新1 天前
【行为型之迭代器模式】游戏开发实战——Unity高效集合遍历与场景管理的架构精髓
unity·设计模式·c#·迭代器模式
敲代码的 蜡笔小新2 天前
【行为型之命令模式】游戏开发实战——Unity可撤销系统与高级输入管理的架构秘钥
unity·设计模式·架构·命令模式
m0_555762902 天前
D-Pointer(Pimpl)设计模式(指向实现的指针)
设计模式