赞
踩
观察者模式是一种行为设计模式,允许你定义一种订阅机制,可在对象事件发生时通知“监控”该对象的其他对象。
主要解决一个对象的状态变化时,需要通知其他对象,并且这些被通知的对象可能是多个且不确定的。
- #!/usr/bin/env python
- # -*- coding: UTF-8 -*-
- __doc__ = """
- 观察者模式
- 例:股票价格监控,当股票价格变化时,通知所有订阅者
- """
-
- from abc import ABC, abstractmethod
- from typing import List
-
-
- class Subject(ABC):
- """发布者基类"""
-
- @abstractmethod
- def register_observer(self, observer):
- pass
-
- @abstractmethod
- def remove_observer(self, observer):
- pass
-
- @abstractmethod
- def notify_observers(self):
- pass
-
-
- class Observer(ABC):
- """订阅者基类"""
-
- @abstractmethod
- def update(self):
- pass
-
-
- class StockPriceSubject(Subject):
- """具体发布者"""
-
- def __init__(self):
- self._observers: List[Observer] = []
- self._price = 0.0
-
- def register_observer(self, observer):
- self._observers.append(observer)
-
- def remove_observer(self, observer):
- self._observers.remove(observer)
-
- def notify_observers(self):
- for observer in self._observers:
- observer.update()
-
- def set_price(self, price):
- self._price = price
- self.notify_observers()
-
- def get_price(self):
- return self._price
-
-
- class Investor(Observer):
- """具体订阅者"""
-
- def __init__(self, name, subject):
- self._name = name
- self._subject = subject
-
- def update(self):
- price = self._subject.get_price()
- print(f"{self._name} 收到新价格: {price}")
-
-
- if __name__ == "__main__":
- """
- 张三 收到新价格: 100.0
- 李四 收到新价格: 100.0
- ------------------------------
- 张三 收到新价格: 110.0
- """
- stock_subject = StockPriceSubject()
-
- investor1 = Investor("张三", stock_subject)
- investor2 = Investor("李四", stock_subject)
-
- stock_subject.register_observer(investor1)
- stock_subject.register_observer(investor2)
- # 股票变动自动通知订阅者
- stock_subject.set_price(100.0)
-
- print("-" * 30)
-
- # 李四取消订阅订阅
- stock_subject.remove_observer(investor2)
- stock_subject.set_price(110.0)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。