观察者模式 Python版--第14章

45 篇文章 0 订阅

双向耦合的代码

class Secretary:
    observers = []
	action = None
    def Attach(self, observer):    
	    self.observers.append(observer)
    def Notify(self):
        for o in observers:
            o.Update()		
    def SecretaryAction(self, value):
	self.action = value
        return self.action	
	
class StockObserver:
    def __init__(self, name , sub):
        self.name = name
        self.sub = sub
    def Update(self):
        print self.sub.SecretaryAction,self.name, "close stock, keep working"

if __name__ == "__main__":
    s = Secretary()	
    c1 = StockObserver("xiaohua", s)
    c2 = StockObserver("xiaoli", s)
    s.Attach(c1)
    s.Attach(c2)
    s.SecretaryAction("Boss is coming!")
    s.Notify()	
解耦合实践---增加了抽象的观察者


class Observer:
    def __init__(self, name, sub):
	    self.name = name
		self.sub = sub
	def Update(self):
	    print sub.SecretaryAction,self.name
class StockObserver(Observer):
    def __init__(self, name, sub):
        Observer.__init__(name, sub)
    def Update(self):
        print "stop stock, keep working"
    
class NBAObserver(Observer):
    def __init__(self, name, sub):
        Observer.__init__(name, sub)    
    def Update(self):
        print "stop watching NBA, keep working"
观察者模式(发布-订阅模式)



class Subject:
    observers = []
    def Attach(self, observer):
	 self.observers.append(observer)
    def Detach(self, observer):
        self.observers.remove(observer)	   
    def Notify(self)
        for o in self.observers:
            o.Update()
		
class ConcreteSubject(Subject):
    subjectState = None
    def SetSubjectState(self, state):
        self.subjectState = state
    def GetSubjectState(self):
        return 	self.subjectState
    def SubjectState(self, state):
        self.SetSubjectState(state)
        self.GetSubjectState()		
		
class Observer:
    def Update(self):
	 pass

class ConcreteObserver(Observer):
    def __init__(self, sub, name):
        self.sub = sub
        self.name = name
    def Update(self):
        self.state = self.sub.subjectState
        print "the new state of observer is ", 	self.state
    def SetState(self, state):
        self.state = state
    def GetState(self):
        return 	self.state
    def Subject(self, state):
        self.SetState(state)
        self.GetState()			

if __name__ =="__main__":
    s = ConcreteSubject()
    s.Attach(ConcreteObserver(s,"X"))
    s.Attach(ConcreteObserver(s,"Y")) 
    s.Attach(ConcreteObserver(s,"Z")) 
    s.SubjectState = "ABC"
    s.Notify()

一个抽象模型有两个方面,其中一个方面依赖于另一方面,这时用观察者模式可以将这两者封装在独立的对象中使它们各自独立地改变和复用。

观察者模式所做的工坐其实就是在解除耦合。让耦合的双方都依赖于抽象,而不是依赖于具体。从而使得各自的变化都不会影响到另一边的变化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值