Subject(目標)ios
Observer(觀察者)spa
ConcreteSubject(具體目標)code
ConcreteObserver(具體觀察者)server
觀察者模式按照如下方式進行協做:對象
#include <iostream> #include <list> using namespace std; class Observer { public: virtual void Update(int) = 0; virtual void showState() = 0; }; class Subject { public: //添加某個觀察者 virtual void Attach(Observer *) = 0; //刪除某個觀察者 virtual void Detach(Observer *) = 0; virtual void Notify() = 0; }; class ConcreteObserver : public Observer { public: ConcreteObserver(Subject *pSubject) : m_pSubject(pSubject){} //根據被觀察物的狀態更新本身的狀態 void Update(int value) { state = value; } void showState() { cout << "The State of ob:" << state << endl; } private: Subject *m_pSubject; int state; }; class ConcreteObserver2 : public Observer { public: ConcreteObserver2(Subject *pSubject) : m_pSubject(pSubject){} //根據被觀察物的狀態更新本身的狀態 void Update(int value) { state = value; } void showState() { cout << "The State of ob2:" << state << endl; } private: //指向一個物體 Subject *m_pSubject; int state; }; class ConcreteSubject : public Subject { public: void Attach(Observer *pObserver); void Detach(Observer *pObserver); void Notify(); void SetState(int state) { m_iState = state; } private: //擁有的觀察者 list<Observer *> m_ObserverList; //當前物體的狀態 int m_iState; }; void ConcreteSubject::Attach(Observer *pObserver) { m_ObserverList.push_back(pObserver); } void ConcreteSubject::Detach(Observer *pObserver) { m_ObserverList.remove(pObserver); } //更新全部觀察者的狀態 void ConcreteSubject::Notify() { list<Observer *>::iterator it = m_ObserverList.begin(); while (it != m_ObserverList.end()) { (*it)->Update(m_iState); ++it; } } int main() { // 建立一個實體 ConcreteSubject *pSubject = new ConcreteSubject(); // 建立所屬該實體的觀察者 Observer *pObserver = new ConcreteObserver(pSubject); Observer *pObserver2 = new ConcreteObserver2(pSubject); // 設置物體狀態 pSubject->SetState(2); // 註冊該物體的觀察者 pSubject->Attach(pObserver); pSubject->Attach(pObserver2); //更新觀察者的狀態 pSubject->Notify(); pObserver->showState(); pObserver2->showState(); // 刪除觀察者 pSubject->Detach(pObserver); //更新物體狀態 pSubject->SetState(3); //更新觀察者狀態 pSubject->Notify(); pObserver->showState(); pObserver2->showState(); delete pObserver; delete pObserver2; delete pSubject; system("pause"); return 0; }