双向耦合的代码
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()
一个抽象模型有两个方面,其中一个方面依赖于另一方面,这时用观察者模式可以将这两者封装在独立的对象中使它们各自独立地改变和复用。
观察者模式所做的工坐其实就是在解除耦合。让耦合的双方都依赖于抽象,而不是依赖于具体。从而使得各自的变化都不会影响到另一边的变化。