首頁  >  文章  >  後端開發  >  Python學習觀察者模式

Python學習觀察者模式

little bottle
little bottle轉載
2019-04-28 10:41:101741瀏覽

本篇文章主要講述了Python的觀察者模式,程式碼具有一定參考價值,有興趣的盆友可以了解一下,希望對你能有所幫助。

需求:員工上班在偷偷看股票,拜託前台一旦老闆進來,就通知他們,讓他們停止看股票。

這裡有兩類人,一類是觀察者,即員工,一類是通知者,即前台,員工在觀察前台的狀態,前台負責通知員工最新的動態。


#encoding=utf-8
__author__ = 'kevinlu1010@qq.com'

class Receptionist():
    def __init__(self):
        self.observes=[]
        self.status=''
    def attach(self,observe):
        self.observes.append(observe)
    def notify(self):
        for observe in self.observes:
            observe.update()

class StockObserve():
    def __init__(self,name,receptionist):
        self.name=name
        self.receptionist=receptionist
    def update(self):
        print '%s,%s停止看股票'%(self.receptionist.status,self.name)

if __name__=='__main__':
    receptionist=Receptionist()
    observe1=StockObserve('张三',receptionist)
    observe2=StockObserve('李四',receptionist)
    receptionist.attach(observe1)
    receptionist.attach(observe2)

    receptionist.status='老板来了'
    receptionist.notify()

這裡的兩個類別的耦合是非常大的,它們是相互依賴的。一方面是前台類別的notify方法會呼叫股票觀察者類別的update方法,另一方面,觀察者類別會存取呼叫前台類別的status屬性來取得最新的動態。

當需求變動時,例如現在老闆也可以是通知者,員工除了看股票,還會看nba,如果增加一個Boss類和NBAObserver類,這樣這四個類的耦合就會非常緊密,後期維護將非常困難,所以當遇到這種緊密耦合的情況時,就需要將它們耦合的部分抽象成一個父類,這樣後期維護就會輕鬆很多


#encoding=utf-8
__author__ = 'kevinlu1010@qq.com'
from abc import ABCMeta, abstractmethod

class Subject():
    __metaclass__ = ABCMeta
    observers=[]
    status=''
    @abstractmethod
    def attach(self,observer):
        pass
    @abstractmethod
    def detach(self,observer):
        pass
    @abstractmethod
    def notify(self):
        pass

class Observer():
    __metaclass__ = ABCMeta
    def __init__(self,name,sub):
        self.name=name
        self.sub=sub
    @abstractmethod
    def update(self):
        pass

class Boss(Subject):
    def __init__(self):
        pass
    def attach(self,observer):
        self.observers.append(observer)

    def detach(self,observer):
        self.observers.remove(observer)
    def notify(self):
        for observer in self.observers:
            observer.update()

class StockObserver(Observer):
    def update(self):
        print '%s,%s停止看股票'%(self.sub.status,self.name)
class NBAObserver(Observer):
    def update(self):
        print '%s,%s停止看NBA'%(self.sub.status,self.name)

if __name__=='__main__':
    boss=Boss()
    observe1=StockObserver('张三',boss)
    observe2=NBAObserver('李四',boss)
    boss.attach(observe1)
    boss.attach(observe2)
    boss.detach(observe2)
    boss.status='我是老板,我来了'
    boss.notify()

 相關教學:Python影片教學

#

以上是Python學習觀察者模式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:cnblogs.com。如有侵權,請聯絡admin@php.cn刪除