示例:
from common import Observer, Observable
class Boss(Observer):
def __init__(self, name):
self.name = name
def update(self, observable, *args, *kwargs):
print("%s recive %s work report: %s" % (self.name, args[1], args[2]))
class Employee(Observable):
def __init__(self, name):
self.name = name
def submit_work_report(self, report):
self.notifyObservers(self, self.name, report)
Henry = Boss("Henry")
Tony = Employee("Tony")
Jimmy = Employee("Jimmy")
Tony.addObserver(Henry)
Jimmy.addObserver(Henry)
Tony.submit_work_report("2000-01-01 work over")
# Henry recive Tony work report: 2000-01-01 work over
Jimmy.submit_work_report("2000-01-01 work deferral")
# Henry recive Jimmy work report: 2000-01-01 work deferral
Jimmy.delObserver(Henry)
Leaf = Boss("Leaf")
Jimmy.addObserver(Leaf)
Jimmy.submit_work_report("2001-01-01 work over")
# Leaf recive Jimmy work report: 2001-01-01 work over