废话少说,直接上代码。释义的话,各位看官可自行百度。这个观察者模式的本质,就是将所有观察者对象放进一个list中,发送给观察者的消息,统一使用 NOTIFY_OBSERVER 发给他们。下面就是代码:
#ifndef OBSERVER_H
#define OBSERVER_H
#include <list>
#include "singletonbase.h"
using namespace std;
class CObserver
{
public:
virtual int OnNotify(int msg1, int msg2, int msg3, int msg4) = 0;
};
class CSubject
{
public:
virtual int Notify(int msg1, int msg2, int msg3, int msg4) = 0;
virtual void Attach(CObserver *observer) = 0;
virtual void Dettach(CObserver *observer) = 0;
};
class ConcreteSubject : public CSubject
{
REGISTER_SINGLETON(ConcreteSubject)
public:
__inline int Notify(int msg1, int msg2, int msg3, int msg4)
{
int bret = -1, bret1;
list<CObserver *>::iterator it = m_list_observer.begin();
for(; it != m_list_observer.end(); it++)
{
bret1 = (*it)->OnNotify(msg1, msg2, msg3, msg4);
if(bret1 != -1)
{
bret = bret1;
}
}
return bret;
}
public:
__inline void Attach(CObserver *observer)
{
m_list_observer.push_back(observer);
}
__inline void Dettach(CObserver *observer)
{
m_list_observer.remove(observer);
}
protected:
list<CObserver*> m_list_observer;
};
#define REGISTER_OBSERVER(observer) \
GET_SINGLETON_INSTANCE(ConcreteSubject)->Attach(observer)
#define REMOVE_OBSERVER(observer) \
GET_SINGLETON_INSTANCE(ConcreteSubject)->Dettach(observer)
#define NOTIFY_OBSERVER(param1, param2, param3, param4) \
GET_SINGLETON_INSTANCE(ConcreteSubject)->Notify(param1, param2, param3, param4)
#endif
可以看出,这个 NOTIFY_OBSERVER 宏函数,是直接调用派生类的OnNotify函数的。所以,这里要注意多线程的情况。最好就是避免在多线程中使用这个接口。