1) 观察者模式定义
略,各种设计模式的书上都有定义。
2) 观察者模式一般实现
观察者模式一般实现,都是“被观察者”保存一个“观察者”的列表,循环这个列表来通知“观察者”。代码,其中使用了boost的智能指针shared_ptr:
- #include <iostream>
- #include <list>
- #include "boost/shared_ptr.hpp"
- using namespace std;
- using namespace boost;
- //观察者基类
- class Observer
- {
- public:
- //处理被观察者的通知
- virtual void update(const int i) = 0;
- };
- //观察者类A
- class ObserverA : public Observer
- {
- public:
- virtual void update(const int i)
- {
- cout << "ObserverA.update(" << i << ")" << endl;
- }
- };
- //观察者类B
- class ObserverB : public Observer
- {
- public:
- virtual void update(const int i)
- {
- cout << "ObserverB.update(" << i << ")" << endl;
- }
- };
- //被观察者基类
- class Subject
- {
- public:
- virtual ~Subject()
- {
- }
- //注册观察者
- virtual void reg(const shared_ptr<Observer>& pObs) = 0;
- //取消注册观察者
- virtual void unreg(const shared_ptr<Observer>& pObs) = 0;
- //通知观察者
- virtual void notify(const int i) = 0;
- };
- //被观察者类A
- class SubjectA : public Subject
- {
- public:
- virtual void reg(const shared_ptr<Observer>& pObs)
- {
- m_lstObs.push_back(pObs);
- }
- virtual void unreg(const shared_ptr<Observer>& pObs)
- {
- for (list<shared_ptr<Observer> >::iterator it = m_lstObs.begin();
- it != m_lstObs.end();)
- {
- if (pObs == *it) m_lstObs.erase(it++);
- else ++it;
- }
- }
- virtual void notify(const int i)
- {
- for (list<shared_ptr<Observer> >::iterator it = m_lstObs.begin();
- it != m_lstObs.end(); ++it)
- {
- (*it)->update(i);
- }
- }
- protected:
- //观察者类别
- list<shared_ptr<Observer> > m_lstObs;
- };
- int main()
- {
- //被观察者pSubA
- shared_ptr<Subject> pSubA(new SubjectA);
- //观察者pObsA
- shared_ptr<Observer> pObsA(new ObserverA);
- //观察者pObsB
- shared_ptr<Observer> pObsB(new ObserverB);
- //注册pObsA
- pSubA->reg(pObsA);
- //注册pObsB
- pSubA->reg(pObsB);
- //通知
- pSubA->notify(1); //显示
- //ObserverA.update(1)
- //ObserverB.update(1)
- //取消pObsA的注册
- pSubA->unreg(pObsA);
- //通知
- pSubA->notify(2); //显示
- //ObserverB.update(2)
- return 0;
- }
3) 观察者模式Boost.Signals实现
Boost.Signals是基于函数指针或函数对象来实现观察者模式的。其中Boost.Signals2是线程安全版本。代码:
- #include <iostream>
- #include <list>
- #include "boost/shared_ptr.hpp"
- #include "boost/signal.hpp"
- using namespace std;
- using namespace boost;
- //使用函数对象来实现
- //观察者类A
- class ObserverA
- {
- public:
- void operator()(const int i)
- {
- cout << "ObserverA(" << i << ")" << endl;
- }
- };
- //观察者类B
- class ObserverB
- {
- public:
- void operator()(const int i)
- {
- cout << "ObserverB(" << i << ")" << endl;
- }
- };
- int main()
- {
- //被观察者sig
- signal<void (const int)> sig;
- //注册观察者ObserverA
- signals::connection connA = sig.connect(ObserverA());
- //注册观察者ObserverB
- sig.connect(ObserverB());
- //通知
- sig(1); //显示
- //ObserverA(1)
- //ObserverB(1)
- //取消obsA的注册
- connA.disconnect();
- //通知
- sig(2); //显示
- //ObserverB(2)
- return 0;
- }
Boost.Signals还支持被观察者分组,可以对整个组进行“通知”、取消注册。另外,Boost.Signals需要编译才能使用。