设计模式 - Observer
意图:定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时, 所有依赖于它的对象都得到通知并被自动更新。
class Subject; class Observer { public: Observer() {} virtual ~Observer() {} virtual void Update(Subject* subject) = 0; }; class Subject { public: Subject():subject_state(0), observers() {} virtual ~Subject() {} int GetState() { return this->subject_state; } void Attach(Observer* observer) { this->observers.push_back(observer); } void Notify() { for(list<Observer*>::iterator it=observers.begin(); it!=observers.end(); ++it) { (*it)->Update(this); } }
protected: int subject_state; list<Observer*> observers; }; class ConcreteSubject: public Subject { public: ConcreteSubject() {} ~ConcreteSubject() {} void Changed() { ++subject_state; Notify(); } }; class ConcreteObserverA: public Observer { public: ConcreteObserverA(): observer_state(0) {} ~ConcreteObserverA() {} void Update(Subject* subject) { cout<<"ConcreteObserverA::Update()"<<endl; this->observer_state = subject->GetState(); } private: int observer_state; }; class ConcreteObserverB: public Observer { public: ConcreteObserverB(): observer_state(0) {} ~ConcreteObserverB() {} void Update(Subject* subject) { cout<<"ConcreteObserverB::Update()"<<endl; this->observer_state = subject->GetState(); } private: int observer_state; };