小工具知识网

当前位置: 首页 > 行业知识 > 设计模式之观察者模式

行业知识

设计模式之观察者模式

2026-11-08 15:31:43 来源:互联网转载

观察者模式(Observer)

定义

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

使用场景

主要角色

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

类图

示例代码

public interface Subject {    void addObserver(Observer observer);    void removeObserver(Observer observer);    void notifyObservers();}
public class WeatherStation implements Subject {    private List 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);        }    }}
public interface Observer {    void update(String temperature, String condition);}
public class TemperatureDisplay implements Observer {    @Override    public void update(String temperature, String condition) {        System.out.println("Temperature Display: Current Temperature is " + temperature);    }}
public class WeatherConditionDisplay implements Observer {    @Override    public void update(String temperature, String condition) {        System.out.println("Weather Condition Display: Current Weather Condition is " + condition);    }}
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°CWeather Condition Display: Current Weather Condition is Sunny

上一篇:虎虎云怎么样?香港云服务器最新优惠是什么?香港云服务器秒杀价16元起

下一篇:独家揭秘海盗湾下载秘籍,轻松获取海量资源!