【项目实战】设计模式之观察者模式,Observer 行为

一、观察者模式

1.1 观察者模式是什么?

观察者模式是一种设计模式,它定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。当主题对象的状态发生改变时,所有观察者对象都会自动更新自己。

观察者模式定义了一种一队多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态上发生变化时,会通知所有观察者对象,使他们能够自动更新自己。

1.2 观察者模式的主要角色

观察者模式的主要角色包括:

1.2.1 主题对象(Subject)

被观察者,如果有状态的变化,会通知所有的观察者对象。

1.2.2 观察者对象(Observer)

观察者,订阅主题对象的状态变化,当主题对象状态发生变化时,观察者对象会被通知。

1.3 观察者模式的基本流程

观察者模式的基本流程如下:

  • 主题对象订阅观察者对象,观察者对象开始监听主题对象的状态变化。
  • 主题对象状态发生变化,观察者对象收到通知并更新自己。

二、使用举例

以下是使用Java编写的简单观察者模式示例代码:

import java.util.ArrayList;
import java.util.List;

interface Subject {
    
    
    void attach(Observer observer);
    void detach(Observer observer);
    void notifyObservers();
}

class WeatherData implements Subject {
    
    
    private List<Observer> observers = new ArrayList<>();
    private String weatherCondition;

    public WeatherData(String weatherCondition) {
    
    
        this.weatherCondition = weatherCondition;
    }

    public void attach(Observer observer) {
    
    
			(weatherCondition);
        }
    }
}

interface Observer {
    
    
    void update(String weatherCondition);
}

class WeatherStation {
    
    
    private Subject weatherData;

    public WeatherStation(Subject weatherData) {
    
    
        this.weatherData = weatherData;
    }

    public void reportWeather(String weatherCondition) {
    
    
        weatherData.notifyObservers();
    }
}

class Radio implements Observer {
    
    
    private WeatherStation weatherStation;

    public Radio(WeatherStation weatherStation) {
    
    
        this

class Television implements Observer {
    
    
    private WeatherStation weatherStation;

    public Television(WeatherStation weatherStation) {
    
    
        this.weatherStation = weatherStation;
        weatherStation.attach(this);
    }

    @Override
    public void update(Sunny");
        WeatherStation weatherStation = new WeatherStation(weatherData);
        Radio radio = new Radio(weatherStation);
         Television television = new Television(weatherStation);
         weatherData.notifyObservers();
    }
}

在这个示例中,Subject接口定义了观察者模式中的主题对象,WeatherData类实现了Subject接口并代表天气数据。WeatherStation类是观察者模式中的具体观察者,它与Radio和Television类建立关系,并在其reportWeather方法中调用主题对象的notifyObservers方法,通知所有观察者更新状态。

在main函数中,我们创建了WeatherData对象、WeatherStation对象、Radio对象和Television对象,并在WeatherData对象的notifyObservers方法被调用时,观察者对象会更新自己的状态。

猜你喜欢

转载自blog.csdn.net/wstever/article/details/129890052