觀察者模式中的主題對象通常存在着一個其餘服務依賴的核心服務,而且維護着其餘依賴此核心服務的對象列表(即觀察者或監視者列表),當主題對象發生變化時,觀察者應該改變本身的狀態或者進行某些操做app
觀察者模式中的三個角色:spa
主題的兩種通知方式:code
觀察者模式的優勢:對象
其餘注意點:blog
簡單示例:接口
from abc import ABCMeta, abstractmethod class Publisher: """被觀察者:發佈/訂閱關係中的發佈對象""" def __init__(self): self.subscribers = [] self.latest_content = None def set_content(self, content): """有新消息時,發佈新的消息""" self.latest_content = content self.publish() def get_latest_content(self): """獲取最新的消息""" return self.latest_content def register(self, subscriber): """註冊一個新的訂閱者""" self.subscribers.append(subscriber) def publish(self): """發佈消息並通知訂閱的用戶""" for subscriber in self.subscribers: subscriber.notify() class Subscriber(metaclass=ABCMeta): """觀察者的抽象類:須要定義一個通知接口,用於發佈對象通知訂閱的用戶""" @abstractmethod def notify(self): pass class SubscriberA(Subscriber): """觀察者A:發佈/訂閱關係中的訂閱者,當訂閱的發佈者有新的變化或動態的時候能及時收到通知""" def __init__(self): self.my_publisher = None def subscribe(self, publisher): """訂閱並進行註冊""" self.my_publisher = publisher self.my_publisher.register(self) def notify(self): """獲取最新消息""" latest_content = self.my_publisher.get_latest_content() print(self, latest_content) class SubscriberB(Subscriber): """觀察者B:發佈/訂閱關係中的訂閱者,當訂閱的發佈者有新的變化或動態的時候能及時收到通知""" def __init__(self): self.my_publisher = None def subscribe(self, publisher): """訂閱並進行註冊""" self.my_publisher = publisher self.my_publisher.register(self) def notify(self): """獲取最新消息""" latest_content = self.my_publisher.get_latest_content() print(self, latest_content) if __name__ == '__main__': new_publisher = Publisher() subscriber_a = SubscriberA() subscriber_a.subscribe(new_publisher) subscriber_b = SubscriberB() subscriber_b.subscribe(new_publisher) new_publisher.set_content('This is a new message!')