Python: Observer Pattern
GeovinDuObserver.py
# 观察者模式 Observer Pattern # The Observer class that recieves updates from the ticker on a specific symbol: class TickerObserver(object): def __init__(self, tickerSymbol): self.tickerSymbol = tickerSymbol self.lastPrice = 0.0 def Update(self, symbol, price): if symbol == self.tickerSymbol: self.lastPrice = price def GetTicker(self): return self.tickerSymbol + " : " + str(self.lastPrice) # The ticker subject that sends out updates to all observers: class StockTicker(object): def __init__(self): self.observers = [] def AttachObserver(self, tickerObserver): self.observers.append(tickerObserver) def RemoveObserver(self, tickerObserver): self.observers.remove(tickerObserver) def Notify(self, symbol, price): for observer in self.observers: observer.Update(symbol, price) class Subject: """Represents what is being observed""" def __init__(self): """create an empty observer list""" self._observers = [] def notify(self, modifier=None): """Alert the observers""" for observer in self._observers: if modifier != observer: observer.update(self) def attach(self, observer): """If the observer is not in the list, append it into the list""" if observer not in self._observers: self._observers.append(observer) def detach(self, observer): """Remove the observer from the observer list""" try: self._observers.remove(observer) except ValueError: pass class Data(Subject): """monitor the object""" def __init__(self, name=''): Subject.__init__(self) self.name = name self._data = 0 @property def data(self): return self._data @data.setter def data(self, value): self._data = value self.notify() class HexViewer: """updates the Hexviewer""" def update(self, subject): print('HexViewer十六进制查看器: 实验对象 {} 转换的数据为: 0x{:x}'.format(subject.name, subject.data)) class OctalViewer: """updates the Octal viewer""" def update(self, subject): print('OctalViewer八进制查看器: 实验对象' + str(subject.name) + '转换的数据为 ' + str(oct(subject.data))) class DecimalViewer: """updates the Decimal viewer""" def update(self, subject): print('DecimalViewer十进制查看器: 实验对象 % s 转换的数据为 % d' % (subject.name, subject.data)) """main function"""
main.py 调用:
# 观察者模式 Observer Pattern obj1 = GeovinDuObserver.Data('Data 1') obj2 = GeovinDuObserver.Data('Data 2') view1 = GeovinDuObserver.DecimalViewer() view2 = GeovinDuObserver.HexViewer() view3 = GeovinDuObserver.OctalViewer() obj1.attach(view1) obj1.attach(view2) obj1.attach(view3) obj2.attach(view1) obj2.attach(view2) obj2.attach(view3) obj1.data = 10 obj2.data = 15 print("\n")
输出:
DecimalViewer十进制查看器: 实验对象 Data 1 转换的数据为 10 HexViewer十六进制查看器: 实验对象 Data 1 转换的数据为: 0xa OctalViewer八进制查看器: 实验对象Data 1转换的数据为 0o12 DecimalViewer十进制查看器: 实验对象 Data 2 转换的数据为 15 HexViewer十六进制查看器: 实验对象 Data 2 转换的数据为: 0xf OctalViewer八进制查看器: 实验对象Data 2转换的数据为 0o17
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)