23种设计模式介绍(Python示例讲解)(34)
2023-04-30 来源:飞速影视
以下是观察者模式的 Python 实现:
class Subject: 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, modifier=None): for observer in self._observers: if modifier != observer: observer.update(self)class Observer: def update(self, subject): passclass ConcreteSubject(Subject): def __init__(self): super().__init__() self._state = None @property def state(self): return self._state @state.setter def state(self, state): self._state = state self.notify()class ConcreteObserver(Observer): def __init__(self, name): self._name = name def update(self, subject): print(f"{self._name} received an update: {subject.state}")subject = ConcreteSubject()observer1 = ConcreteObserver("Observer 1")observer2 = ConcreteObserver("Observer 2")subject.attach(observer1)subject.attach(observer2)subject.state = 123subject.detach(observer1)subject.state = 456
本站仅为学习交流之用,所有视频和图片均来自互联网收集而来,版权归原创者所有,本网站只提供web页面服务,并不提供资源存储,也不参与录制、上传
若本站收录的节目无意侵犯了贵司版权,请发邮件(我们会在3个工作日内删除侵权内容,谢谢。)
www.fs94.org-飞速影视 粤ICP备74369512号