Python設計模式之觀察者模式簡單示例

2022-10-06 04:57:09 字數 2410 閱讀 5259

觀察者模式是乙個軟體設計模式,乙個主題物件包涵一系列依賴他的觀察者,自動通知觀察者的主題物件的改變,通常會呼叫每個觀察者的乙個方法。這個設計模式非常適用於分布式事件處理系統。

典型的在觀察者模式下:

1.發布者類應該包涵如下方法:

註冊能夠接收通知的物件

從主物件到註冊物件,通知任何變化

未註冊物件不能夠接收任何通知資訊

2.訂購者類應該包涵如下:

發布者會呼叫乙個訂購者提供的方法,將任何改變告知註冊物件。

3.當乙個事件會觸fwfia發了狀態的改變,發表者會呼叫通知方法

總結:訂閱者可以在發布物件中註冊或者不註冊,如此無論什麼事件發生,都會觸fwfia發發布者通程式設計客棧過呼叫通知方法,去通知訂購者。這個通知只會在事件發生的時候,去通知已經註冊的訂購者。

乙個簡單的python實現:

讓我們實現乙個不同使用者在techforum 上發布技術郵件的例子,當任何使用者發布乙個新的郵件,其他使用者就會接收到新郵件通知。從物件的角度去看,我們應該有乙個 techforum物件,我們需要有另外一些需要使用者物件在techforum上註冊,當新郵件通知的時候,應該傳送郵件標題。

乙個簡單的例子分析會聯想到中介機構和雇主的關係。這就是招聘者和應聘者關係的延伸。通過乙個工作中介會發布不同種類的工作資訊,應聘者會去尋找相關的工作資訊,招聘者也會尋找在中介註冊過的應聘者。

**如下:

class publisher:

def __init__(self):

pass

def register(self):

pass

def unregister(self):

pass

def notifyall(self):

pass

class techforum(publisher):

def __init__(self):

self._listofusers =

self.postname = none

def rwww.cppcns.comegister(self, userobj):

if userobj not in self._listofusers:

self._listofusers.append(userobj)

def unregister(self, userobj):

self._listofusers.remove(userobj)

def notifyall(self):

for objects in self._listofusers:

objects.notify(self.postname)

def writenewpost(self , postname):

self.postname = postname

self.notifyall()

class subscriber:

def __init__(self):

pass

def notify(self):

pass

class user1(subscriber):

def notify(self, postname):

print "user1 notified 程式設計客棧of a new post %s" % postname

class user2(subscriber):

def notify(self, postname):

print "user2 notified of a new post %s" % postname

class sistersites(subscriber):

def __init__(self):

self._sisterwebsites = ["site1" , "site2", "site3"]

def notify(self, postname):

for site in self._sisterwebsites:

print "send nofication to site:%s " % site

if __name__ == "__main__":

techforum = techforum()

user1 = user1()

user2 = user2()

sites = sistersites()

techforum.register(user1)

techforum.register(user2)

techforum.register(sites)

techforum.writenewpost("observe pattern in python")

techforum.unregister(user2)

techforum.writenewpost("mvc pattern in python")

執行結果:

python 設計模式 觀察者 觀察者設計模式

在觀察者設計模式這種模式中,物件被表示為等待事件觸發的觀察者。一旦發生指定的事件,觀察者就會關注該主體。當事件發生時,主體告訴觀察者它已經發生。以下uml圖表示觀察者模式 如何實現觀察者模式?現在讓我們來看看如何實現觀察者模式。參考以下實現 import threading import time ...

Python 設計模式之觀察者模式

觀察者模式之西遊記師徒四人 被觀察者 class imaster object def init self self.prentice list def name self raise notimplementederror 收徒def add prentice self,prentice if i...

python 設計模式之觀察者模式

在現實世界中,許多物件並不是獨立存在的,其中乙個物件的行為發生改變可能會導致乙個或者多個其他物件的行為也發生改變。例如,某種商品的物價 時會導致部分商家高興,而消費者傷心 這樣的例子還有很多,例如小偷與警察,貓和老鼠等 觀察者模式就如乙個聊天室,當你需要收到聊天室的訊息時,你就註冊成為聊天室的成員,...