觀察者模式
當(dāng)我們希望一個(gè)對象的狀態(tài)發(fā)生變化债热,那么依賴與它的所有對象都能相應(yīng)變化(獲得通知),那么就可以用到Observer模式惕它, 其中的這些依賴對象就是觀察者的對象,那個(gè)要發(fā)生變化的對象就是所謂’觀察者’
# 這個(gè)是觀察者基類
class Observe(object):
def __init__(self):
self._observers = []
# 添加依賴的對象
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, modifier=None):
for observer in self._observers:
# 可以設(shè)置過濾條件,對不符合過濾條件的更新
if modifier != observer:
observer.update(self)
# 觀察者類
class Data(Observe):
def __init__(self, name=''):
super(Data, self).__init__()
self.name = name
self._data = 0
# python2.6新增的寫法,獲取屬性為property讯屈,設(shè)置屬性為(假設(shè)屬性名字為x)@x.setter,刪除為@x.deleter
@property
def data(self):
return self._data
@data.setter
def data(self, value):
self._data = value
self.notify()
# 這里有2個(gè)被觀察者绑蔫,也就是依賴的對象运沦,每次Data有改變,這2個(gè)view都會(huì)變動(dòng)
class HexViewer(object):
def update(self, observe):
print 'HexViewer: Observe%s has data 0x%x' % (observe.name, observe.data)
class DecimalViewer(object):
def update(self, observe):
print 'DecimalViewer: Observe%s has data %d' % (observe.name, observe.data)
if __name__ == '__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 "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 "Update data1's view2 Because view1 is be filtered"
data1.notify(modifier=view1)
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