# -*- coding: utf-8 -*-
class Observer:
def __init__(self,observer_id):
self.observer_id = observer_id
def update(self,subject):
print(f'{self.observer_id}: subject updated to: {subject}')
class Subject:
observers=[]
state=''
def update(self,state):
self.state = state
self.notify_all_observers() # 当状态发生更改时通知所有观察者
def add_observer(self,observer):
self.observers.append(observer) # 把观察者添加到通知列表
def notify_all_observers(self):
for observer in self.observers:
observer.update(self)
def __str__(self):
return f"<{self.state}>"
subject_0 = Subject()
observer_0 = Observer('observer_0')
observer_1 = Observer('observer_1')
subject_0.add_observer(observer_0)
subject_0.add_observer(observer_1)
subject_0.update('1')
subject_0.update('2')
观察者模式
最新推荐文章于 2024-09-01 15:47:48 发布