观察者模式
观察者模式思想核心就是:把观察者挂在被观察对象上,当被观察对象状态发生变化时候,依次推送给观察者
eg: 男人在外面死命挣钱(被观察者),老婆女儿两个观察者,一旦男人钱包金额发生变动需要通知老婆女儿
# coding=utf-8
class Man:
def __init__(self):
# 男人怀揣500块出门
self.money = 500
self.family = []
def watching(self, woman):
self.family.append(woman)
def get_money(self, money):
self.money += money
self.push()
def push(self):
for f in self.family:
f.pull(self)
class Woman:
def __init__(self):
pass
def pull(self):
pass
class Daughter(Woman):
def __init__(self):
pass
def pull(self, dad):
print '爸爸好厉害, 挣了{}块钱'.format(dad.money)
class Wife(Woman):
def __init__(self):
pass
def pull(self, dad):
print '才挣{}块钱,怎么养家?'.format(dad.money)
if __name__ == '__main__':
daughter = Daughter()
wife = Wife()
dad = Man()
dad.watching(wife)
dad.watching(daughter)
dad.get_money(1000)
dad.get_money(3000)
运行结果
才挣1500块钱,怎么养家?
爸爸好厉害, 挣了1500块钱
才挣4500块钱,怎么养家?
爸爸好厉害, 挣了4500块钱
看,当dad.watching(wife) or dad.watching(daughter)之后老爸钱包里钱一旦变动,观察者不需要做任何东西,消息就自动推送到观察者身边了。
网友评论