勇敢,世界就会让步。如果有时候你被它打败了,不断地勇敢再勇敢,它就会屈服。
"""观察者模式"""
class Subject(object):
def __init__(self):
self._observers = []
def attach(self, observer):
if observer not in self._observers:
self._observers.append(observer)
def detach(self, observer):
try:
self._observers.remove(observer)
except ValueError:
pass
def notify(self, modifier=None):
for observer in self._observers:
if modifier != observer:
observer.update(self)
class Data(Subject):
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:
def update(self, subject):
print('十六进制查看器: 主题 %s 有数据 0x%x' % (subject.name, subject.data))
class DecimalViewer:
def update(self, subject):
print('十进制查看器: 主题 %s 有数据 %d' %
(subject.name, subject.data))
def main():
data1 = Data('Data 1')
data2 = Data('Data 2')
view1 = DecimalViewer()
view2 = HexViewer()
data1.attach(view1)
data1.attach(view2)
data2.attach(view2)
data2.attach(view1)
print("设置数据1变量 = 10")
data1.data = 10
print("设置数据2变量 = 15")
data2.data = 15
print("设置数据1变量 = 3")
data1.data = 3
print("设置数据2变量 = 5")
data2.data = 5
print("从data1和data2分离HexViewer。")
data1.detach(view2)
data2.detach(view2)
print("设置数据1变量 = 10")
data1.data = 10
print("设置数据2变量 = 15")
data2.data = 15
if __name__ == '__main__':
main()
结果如图: