观察者模式(Observer Pattern)是一种行为型设计模式,在该模式中,对象间的一对多依赖关系被定义。当一个对象状态发生改变时,所有依赖于这些对象的其他对象都会得到通知并自动更新。
以下是使用 Python 语言来解释观察者模式的示例代码:
# 创建主题类 Subject
class Subject:
def __init__(self):
self.observers = []
# 注册观察者
def register(self, observer):
if not isinstance(observer, Observer):
raise TypeError("Invalid observer type")
self.observers.append(observer)
# 移除观察者
def remove(self, observer):
if observer in self.observers:
self.observers.remove(observer)
# 通知所有观察者
def notify_all(self, message):
for observer in self.observers:
observer.update(message)
# 创建观察者类 Observer
class Observer:
def update(self, message):
pass
# 创建具体观察者类 ConcreteObserver1、ConcreteObserver2...
class ConcreteObserver1(Observer):
def update(self, message):
print("ConcreteObserver1 received a notification:", message)
class ConcreteObserver2(Observer):
def update(self, message):
print("ConcreteObserver2 received a notification:", message)
# 测试观察者模式
if __name__ == "__main__":
subject = Subject()
observer1 = ConcreteObserver1()
observer2 = ConcreteObserver2()
subject.register(observer1)
subject.register(observer2)
subject.notify_all("Hello observers!")
运行上述代码后,输出结果如下:
ConcreteObserver1 received a notification: Hello observers!
ConcreteObserver2 received a notification: Hello observers!
网友评论