设计模式----观察者模式
Posted 幻觉czw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式----观察者模式相关的知识,希望对你有一定的参考价值。
#设计模式---观察者模式
#纯属练手仿制,如有错误欢迎拍砖
#delusion's code
#气象站台---小试牛刀
class Subject(object):#被观察的对象
def register(self,observer):
pass
def unregister(self,observer):#移除观察者
pass
def notify(self):#通知观察者
pass
#观察者
class Observer(object):
def update(self,temperature,humidity,pressure):
pass
class Display(object):
def display(self):
pass
class Weather_data(Subject):
def __init__(self):
self.observers = []
def register(self,observer):#注册观察者
if observer not in self.observers:
self.observers.append(observer)
def unregister(self,observer):#移除观察者
if observer in self.observers:
self.observers.remove(observer)
def date_change(self):#当数据发生改变时,通知观察者
for o in self.observers:
o.update(self.temperature,self.humidity,self.pressure)#调用观察者的更新方法
def notify(self):#通知观察者
self.date_change()
def setdata(self,temperature = None,humidity = None,\\ #数据改变
pressure = None):
self.temperature = temperature
self.humidity = humidity
self.pressure = pressure
self.notify()
class CurrentDisplay(Observer,Display):#定义了一个事实更新的观察者
def __init__(self,weather_data = None):
self.weather_data = weather_data
weather_data.register(self)
def update(self,temperature,humidity,pressure):#更新得到的数据
self.temperature = temperature
self.humidity = humidity
self.pressure = pressure
self.display()
def display(self):#显示更新
print 'Current data : temperature == %s, humidity == %s, pressure == %s' \\
% (self.temperature,self.humidity,self.pressure)
class AverageDisplay(Observer,Display):
def __init__(self,weather_data = None):
self.weather_data = weather_data
weather_data.register(self)
self.temperatures = []
self.humidities = []
self.pressures = []
def update(self,temperature,humidity,pressure):
self.temperatures.append(temperature)
self.humidities.append(humidity)
self.pressures.append(pressure)
self.display()
def average(self,datas):
sum = 0
for i in datas:
sum += i
return sum/len(datas)
def display(self):
print 'Average data: temperature == %s,humidity == %s,pressure == %s'\\
% (self.average(self.temperatures),self.average(self.humidities)\\
,self.average(self.pressures))
以上是关于设计模式----观察者模式的主要内容,如果未能解决你的问题,请参考以下文章