觀察者模式:
情境特性:
結構特性:
#!/usr/bin/env python #encoding: utf-8class subject: def __init__(self): self.obs = [] def add_ob(self, ob): self.obs.append(ob) def del_ob(self, ob): self.obs.remove(ob) def notify(self): for ob in self.obs: ob.update()class observer: def __init__(self): pass def update(self): pass class create_subject(subject): def __init__(self): subject.__init__(self) self.substatue = '' class create_ob(observer): def __init__(self, name, csubj): self.name = name self.status = '' self.csubj = csubj def update(self): print '觀察者{%s}的新狀態是{%s}' % (self.name, self.csubj.substatue) if '__main__' == __name__: csub = create_subject() csub.add_ob(create_ob('A', csub)) csub.add_ob(create_ob('B', csub)) csub.add_ob(create_ob('C', csub)) csub.substatue = 'something happen' csub.notify()
結果:
觀察者{A}的新狀態是{something happen}觀察者{B}的新狀態是{something happen}觀察者{C}的新狀態是{something happen}