观察者模式是一种行为设计模式,它定义了对象之间的一对多依赖关系,当一个对象的状态发生变化时,所有依赖于它的对象都会得到通知并自动更新。

观察者模式的特点

  • 低耦合:观察者与被观察者之间解耦,它们之间没有直接的依赖关系。
  • 高内聚:观察者模式将更新逻辑封装在单独的类中,提高了代码的可维护性。
  • 易于扩展:可以通过添加新的观察者或被观察者来扩展系统功能。

观察者模式示例

以下是一个简单的观察者模式示例,展示了如何实现一个天气信息系统:

class WeatherSubject:
    def __init__(self):
        self._observers = []

    def attach(self, observer):
        if observer not in self._observers:
            self._observers.append(observer)

    def detach(self, observer):
        try:
            self._observers.remove(observer)
        except ValueError:
            pass

    def notify(self, temperature, humidity, pressure):
        for observer in self._observers:
            observer.update(temperature, humidity, pressure)


class CurrentConditionsDisplay:
    def __init__(self, subject):
        self._subject = subject
        self._subject.attach(self)
        self._temperature = 0
        self._humidity = 0

    def update(self, temperature, humidity, pressure):
        self._temperature = temperature
        self._humidity = humidity
        self.display()

    def display(self):
        print(f"Current conditions: {self._temperature}F degrees and {self._humidity}% humidity")


# 创建天气主题
weather_data = WeatherSubject()

# 创建当前条件显示
current_conditions = CurrentConditionsDisplay(weather_data)

# 更新天气数据
weather_data.notify(80, 65, 30.4)
weather_data.notify(82, 70, 29.2)

在上面的示例中,WeatherSubject 类是主题,它维护了一个观察者列表,并提供方法来添加、删除和通知观察者。CurrentConditionsDisplay 类是一个观察者,它实现了 update 方法来更新显示的数据。

扩展阅读

想要了解更多关于设计模式的知识,可以阅读《设计模式:可复用面向对象软件的基础》.

图片展示

Weather Pattern