#include "stdafx.h" #include <set> class Observer; class Subject { public: virtual void attachObserver(Observer* o) = 0; virtual void detachObserver(Observer* o) = 0; virtual void notify() = 0; }; class Observer { public: virtual void update(Subject* s) = 0; }; class Window : public Subject { public: void attachObserver(Observer* o) { mObservers.insert(o); } void detachObserver(Observer* o) { mObservers.erase(o); } void notify() { for (std::set<Observer*>::const_iterator it = mObservers.begin(); it!=mObservers.end(); ++it) { (*it)->update(this); } } void OnSize(int w, int h) { mWidth = w; mHeight = h; notify(); } void GetSize(int &w, int &h) { w = mWidth; h = mHeight; } protected: std::set<Observer*> mObservers; int mWidth, mHeight; }; class Client : public Observer { public: void update(Subject* s) { int w, h; Window* pWnd = (Window*)s; pWnd->GetSize(w, h); mWidth = w / 2; mHeight = h / 2; } private: int mWidth, mHeight; }; class Button : public Observer { public: void update(Subject* s) { int w, h; Window* pWnd = (Window*)s; pWnd->GetSize(w, h); mWidth = w / 8; mHeight = h / 8; } private: int mWidth, mHeight; }; int _tmain(int argc, _TCHAR* argv[]) { Window w; Client c; w.attachObserver(&c); Button btn; w.attachObserver(&btn); w.OnSize(50, 20); return 0; }