Observer模式定義對象間的一對多的依賴關系,當一個對象的狀態發生改變時,所有依賴於它的對象都得到通知並被自動更新。
Observer模式定義的是一種一對多的關系,一是Subject類,而多則是Obesrver類,當Subject類的狀態發生變化的時候通知與之對應的Obesrver類們也去相應的更新狀態,同時支持動態的添加和刪除Observer對象的功能。
Subject類一般都是采用鏈表等容器來存放Observer對象指針;
Observer類一般是抽取Observer對象的一些公共的屬性形成Observer基類,而Subject中保存的則是Observer類對象的指針,這樣就使Subject和具體的Observer實現了解耦;
下面是測試代碼:
- #ifndef OBSERVER_H
- #define OBSERVER_H
- #include <list>
- #include <pthread.h>
- using namespace std;
- typedef int STATUS;
-
- #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } }
- #define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } }
-
- class Mutex
- {
- public:
- Mutex()
- {
- pthread_mutex_init(&m_lock,NULL);
- }
-
- ~Mutex()
- {
- pthread_mutex_destroy(&m_lock);
- }
-
- void Lock()
- {
- pthread_mutex_lock(&m_lock);
- }
-
- void UnLock()
- {
- pthread_mutex_unlock(&m_lock);
- }
-
- private:
- pthread_mutex_t m_lock;
- };
-
- class IObserver;
- class ISubject
- {
- public:
- ISubject() : m_statusSubject(-1) {}
- virtual ~ISubject();
- void Register(IObserver *pObserver);
- void UnRegister(IObserver *pObserver);
- virtual void SetStatus(STATUS status) = 0;
- virtual STATUS GetStatus() = 0;
- virtual void Notify() = 0;
-
- protected:
- STATUS m_statusSubject;
- Mutex m_mutex;
- list<IObserver*> m_listObserver;
- };
-
- class Subject : public ISubject
- {
- public:
- Subject() {}
- virtual ~Subject() {};
- virtual void SetStatus(STATUS status);
- virtual STATUS GetStatus();
- virtual void Notify();
- };
-
- class IObserver
- {
- public:
- IObserver() : m_statusObserver(-1) {}
- virtual ~IObserver() {}
- virtual void Update(ISubject* pSubject) = 0;
- protected:
- STATUS m_statusObserver;
- };
-
- class Observer : public IObserver
- {
- public:
- Observer() {}
- virtual ~Observer() {}
- virtual void Update(ISubject* pSubject);
- };
- #endif