更新时间:2024-04-25 来源:黑马程序员 浏览量:
观察者模式是一种行为设计模式,用于定义对象之间的一对多依赖关系,当一个对象的状态发生改变时,其所有依赖者(观察者)都会收到通知并自动更新。下面是一个简单的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, *args, **kwargs): for observer in self._observers: observer.update(*args, **kwargs) class Observer: def update(self, *args, **kwargs): raise NotImplementedError("Subclasses must implement update method.") class ConcreteSubject(Subject): def __init__(self, state): super().__init__() self._state = state @property def state(self): return self._state @state.setter def state(self, value): self._state = value self.notify(self._state) class ConcreteObserver(Observer): def __init__(self, name): self._name = name def update(self, *args, **kwargs): new_state = args[0] print(f"Observer {self._name} received update. New state is {new_state}") # 使用示例 if __name__ == "__main__": subject = ConcreteSubject("initial state") observer1 = ConcreteObserver("Observer 1") observer2 = ConcreteObserver("Observer 2") subject.attach(observer1) subject.attach(observer2) subject.state = "new state" subject.detach(observer1) subject.state = "final state"
在这个示例中,Subject类是主题或被观察者,负责管理观察者列表并通知它们状态的变化。Observer类是观察者的基类,定义了一个抽象的更新方法。ConcreteSubject和ConcreteObserver分别是具体的实现类,其中 ConcreteSubject持有一个状态,并在状态改变时通知观察者。