#!/usr/bin/python
# coding:utf8
'''
Observer
'''
class Subject(object): # 发布者基类
def __init__(self):
self._observers = []
self._modifier = []
def attach(self, observer): # 添加
if not observer in self._observers:
self._observers.append(observer)
def detach(self, observer): # 删除
try:
self._observers.remove(observer)
except ValueError:
pass
def notify(self): # 通知
for observer in self._observers:
if observer not in self._modifier:
observer.update(self)
# 发布者
class Data(Subject):
def __init__(self, name=''):
super(Data, self).__init__()
self.name = name
self._data = 0
def defriend(self, observer): # 拉黑
if not observer in self._modifier:
self._modifier.append(observer)
def friend(self, observer): # 取消拉黑
try:
self._modifier.remove(observer)
except ValueError:
pass
@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('HexViewer: Subject %s has data 0x%x' % # 十六进制
(subject.name, subject.data))
class DecimalViewer:
def update(self, subject):
print('DecimalViewer: Subject %s has data %d' % # 十进制
(subject.name, subject.data))
# Example usage...
def main():
data1 = Data('Data 1')
data2 = Data('Data 2')
view1 = DecimalViewer()
view2 = HexViewer()
data1.attach(view1)
data1.defriend(view1)
data1.attach(view2)
data2.attach(view2)
data2.attach(view1)
print("Setting Data 1 = 10")
data1.data = 10
print("Setting Data 2 = 15")
data2.data = 15
print("Setting Data 1 = 3")
data1.data = 3
print("Setting Data 2 = 5")
data2.data = 5
print("Detach HexViewer from data1 and data2.")
data1.detach(view2)
data2.detach(view2)
print("Setting Data 1 = 10")
data1.data = 10
print("Setting Data 2 = 15")
data2.data = 15
if __name__ == '__main__':
main()
网友评论