Python設計模式之觀察者模式

定義

觀察者模式也叫發佈訂閱模式,定義了對象之間一對多依賴,當一個對象改變狀態時,這個對象的所有依賴者都會收到通知並按照自己的方式進行更新。

觀察者設計模式是最簡單的行爲模式之一。在觀察者設計模式中,對象(主題)維護了一個依賴(觀察者)列表,以便主題可以使用觀察者定義的任何方法通知所有觀察者它所發生的變化。

**舉個生活中的小例子:**職員們趁老闆不在,都在搞着自己與工作無關的事情,同時觀察着前臺小姐姐,前臺小姐姐在老闆回來的時候,發佈通知讓各同事回到工作狀態。

使用場景

在廣播或者發佈訂閱系統的情形中,你會看到觀察者設計模式的用法,它的主要使用場景如下:

主要目標

代碼實現

1、創建觀察者類
class Watcher:
    #初始化具體的成員
    def __init__(self,id,name):
        self.id=id
        self.name=name

    #向具體的成員發送消息的方法
    def send(self,msg):
        print(str(self.name)+ "-" + str(self.id)+" recive the message is: "+msg)
2、創建主題類
class Subject:
    #初始化一個主題列表
    def __init__(self):
        self.queues=[]

    #將訂閱者添加到隊列中
    def add_queue(self,sub):
        self.queues.append(sub)
        return self.queues

    #從訂閱的主題裏面移除
    def remove_queue(self,sub):
        self.queues.remove(sub)
        self.queues

    #發送通知給相關的主題訂閱者
    def notice(self,msg):
        for queue in self.queues:
            queue.send(msg)

if __name__ == '__main__':
    #實例化具體的Watcher對象,用於去訂閱和接收相關信息
    tom=Watcher(1001,"tom")
    tony=Watcher(1002,"tony")
    jack=Watcher(1003,"jack")

    #實例化Subject對象,定義爲添加天氣主題
    weather=Subject()
    weather.add_queue(tom)
    weather.add_queue(tony)

    #實例化Subject對象,定義爲添加軍事主題
    military=Subject()
    military.add_queue(tony)
    military.add_queue(jack)

    #給訂閱者發佈天氣消息
    weather.notice("it's rain")
    military.notice("it's peace")

    #將tony從weather and military主題中取消訂閱
    weather.remove_queue(tony)
    military.remove_queue(tony)

    #取消訂閱後給剩下的訂閱者發佈消息
    weather.notice("it's windy")
    military.notice("it's war")
3、執行結果輸出
tom-1001 recive the message is: it's rain
tony-1002 recive the message is: it's rain
tony-1002 recive the message is: it's peace
jack-1003 recive the message is: it's peace
tom-1001 recive the message is: it's windy
jack-1003 recive the message is: it's war
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/2Txss_b7ZbMcrLOtTBW1kg