本文共 3924 字,大约阅读时间需要 13 分钟。
class Observer {public: virtual void Update(int event) = 0;};
const int EVENT_LOGIN = 1;class UIMng : public Observer {public: virtual void Update(int event) { if (EVENT_LOGIN == event) { ...... } }};class DatabaseMng: public Observer {public: virtual void Update(int event);};class BroadcastMng: public Observer {public: virtual void Update(int event);};DatabaseMng, BroadcastMng等都和UIMng类类似。class Subject {public: void attach(Observer* o) { if (o != NULL) { mObservers.push_back(o); } } void detach(Observer* o) { list::iterator it; if (o != NULL) { for (it = mObservers.begin(); it !=mObservers.end(); it++) { if (*it == o) { mObservers.erase(it); } } } } void Notify(int event) { list ::iterator it; for (it =mObservers.begin(); it !=.end(); it++) { if (*it != NULL) { (*it)->Update(event); } } }private: list mObservers;};
class LoginSubject : public Subject {public: void OnLogin() { Notify(EVENT_LOGIN); }};
Observer* uiMng = new UIMng();Observer* dbMng = new DatabaseMng();Observer* bcMng = new BroadcastMng();LoginSubject login;login.attach(uiMng);login.attach(dbMng );login.attach(bcMng );
class LoginObserver{public: virtual void Update() = 0;};
class Subject {public: void attach(Observer* o) { if (o != NULL) { mObservers.push_back(o); } } void detach(Observer* o) { list::iterator it; if (o != NULL) { for (it = mObservers.begin(); it !=mObservers.end(); it++) { if (*it == o) { mObservers.erase(it); } } } } void Notify() { list ::iterator it; for (it =mObservers.begin(); it !=.end(); it++) { if (*it != NULL) { (*it)->Update(this); } } } int GetStatus() { ...... }private: list mObservers;};class UIMng : public Observer {public: virtual void Update(Subject* sub) { ...... int status = sub->GetStatus(); ...... }};
转载地址:http://oceqj.baihongyu.com/