观察者模式
class Subject: def attach(self): pass def remove(self): pass def noticefy(self): pass def getState(self): pass def setState(self): pass class ConcreteSubject(Subject): observer = [] state = '' def attach(self, obj): self.observer.append(obj) def remove(self, obj): self.observer.remove(obj) def noticefy(self): for i in self.observer: i.update() def getState(self): return self.state def setState(self, val): self.state = val class Observer: def update(self): pass class EmailObserver(Observer): def __init__(self, obj): self.subject = obj def update(self): print('email noticefy user', self.subject.getState()) class LogObserver(Observer): def __init__(self, obj): self.subject = obj def update(self): print('log update', self.subject.getState()) if __name__ == '__main__': subject = ConcreteSubject() subject.attach(EmailObserver(subject)) subject.attach(LogObserver(subject)) subject.setState('haha') subject.noticefy()