观察者模式,被观察物自身属性通知观察者。
class Obj(object):
def __init__(self, value):
super().__init__()
self.observers = []
self.dynamic_value = value
def add_observer(self, observer):
self.observers.append(observer)
def remove_observer(self, observer):
self.observers.remove(observer)
def notify_observer(self):
for observer in self.observers:
observer.update()
class Observer(object):
def __init__(self, target):
super().__init__()
self.target = target
def update(self):
print(self.target.dynamic_value)
def main():
obj = Obj("value")
observer = Observer(obj)
obj.add_observer(observer)
obj.dynamic_value = "new_value"
obj.notify_observer()
if __name__ == '__main__':
main()