设计模式——观察者模式
设计模式一种思想
增强了代码可重用性、让代码更容易被他人理解、保证代码可靠
# 观察者模式
观察者模式:
被观察者的某些属性/行为改变时通知观察者进行相应的响应
1.被观察者baby有一个属性need,当这个属性变化通知观察者parents调用
updata方法
2.被观察者parents就要有一个改变属性need的方法setNeed(),
在setNeed()中调用partents的update方法
parents有father和mother两个观察者
为了调用所有观察者的updata方法,将观察者对象
作为baby类的属性的集合
3.baby还需要一个方法遍历所有观察者调用他们自身的方法notify()
for 循环 parents
father.updata()
4.在baby的setNeed()中调用自身的notify(),即可将自身属性/行为的改变
通知所有的观察者
综上所述,我们需要一个公共的接口代表观察者,它有接收到通知时
调用自身的updata方法
一个公共的接口表示被观察者,它有添加观察者的方法
删除观察者的方法,遍历并调用观察者的方法
具体的被观察的属性/行为由实现类去决定
from abc import ABCMeta,abstractmethod class Parents(metaclass=ABCMeta): ''' 观察者的父类 ''' @abstractmethod def update(self,obserceable,obj):#定义抽象方法 pass
class Kid(object): ''' 被观察的父类 ''' def __init__(self): ''' Constructor ''' self.__obdervable = [] def add(self,ob):#添加观察者 if ob != None: self.__obdervable.append(ob) def remove(self,ob):#移除观察者 if ob in self.__obdervable: self.__obdervable.remove(ob) def notify(self,ob = 0):#被观察者状态改变时通知所有的观察者 for o in self.__obdervable: o.update(self,ob)
class Father(Parents): ''' 观察者的子类——father类,baby尿了/哭闹,这个类处理 ''' def update(self,obserceable,obj): #获取baby类的状态 num = obserceable.getTemperature() if isinstance(obserceable, Baby) and num in (4,5) : print('爸爸处理') else: return class Mather(Parents): ''' 观察者的子类——mather类,baby饿了/渴了,这个类处理 ''' def update(self,obserceable,obj): #获取baby类的状态 num = obserceable.getTemperature() if isinstance(obserceable, Baby) and num in (1,2) : print('妈妈处理') else: return
class Baby(Kid): ''' 被观察者的实现类——Baby类 ''' #Baby类的状态 __dic = {1:'饿了',2:'口渴了',3:'困了',4:'又哭又闹',5:'尿了'} def __init__(self): super().__init__() self.__temperature = 3 #baby的状态 def getTemperature(self):#获取baby的状态 return self.__temperature def setTemperature(self,tem):#修改baby的状态 self.__temperature = tem if self.__temperature > 0 and self.__temperature < 6: print('这个婴儿 ' + self.__dic[self.__temperature]) self.notify() return self.__temperature else: print('这是一个假baby') return
#测试代码
baby = Baby() father = Father() mather = Mather() baby.add(father) baby.add(mather) baby.setTemperature(1) baby.setTemperature(2) baby.setTemperature(3) baby.setTemperature(4) baby.setTemperature(5)
baby.setTemperature(6)
这个婴儿 饿了
妈妈处理
这个婴儿 口渴了
妈妈处理
这个婴儿 困了
这个婴儿 又哭又闹
爸爸处理
这个婴儿 尿了
爸爸处理
这是一个假baby

浙公网安备 33010602011771号