设计模式之观察者模式

观察者模式(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
相关推荐
雨中飘荡的记忆2 小时前
观察者模式:从理论到生产实践
java·设计模式
阿波罗尼亚4 小时前
Head First设计模式(十二) 设计原则 复合模式
设计模式
老朱佩琪!4 小时前
Unity原型模式
开发语言·经验分享·unity·设计模式·原型模式
拾忆,想起4 小时前
设计模式三大分类完全解析:构建高质量软件的基石
xml·微服务·设计模式·性能优化·服务发现
老朱佩琪!4 小时前
Unity装饰器设计模式
unity·设计模式
syt_10134 小时前
设计模式之-策略模式
设计模式·bash·策略模式
老鼠只爱大米5 小时前
Java设计模式之代理模式(Proxy)深度解析
java·设计模式·代理模式·proxy pattern·java设计模式·proxypattern
老朱佩琪!5 小时前
Unity适配器模式
unity·设计模式·游戏引擎·适配器模式
syt_10131 天前
设计模式之-代理模式
设计模式·代理模式
拾忆,想起1 天前
设计模式:软件开发的可复用武功秘籍
开发语言·python·算法·微服务·设计模式·性能优化·服务发现