C++设计模式-Observer观察者模式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++设计模式-Observer观察者模式相关的知识,希望对你有一定的参考价值。
#include <iostream> #include <sstream> #include <map> #include <signal.h> #include <stdio.h> #include <memory> #include <vector> #include <set> #include <assert.h> #include <unordered_map> #include <boost/thread.hpp> #include <boost/bind/bind.hpp> #include <queue> #include <Winsock2.h> #include <boost/progress.hpp> #include <boost/date_time/gregorian/gregorian.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/ref.hpp> #include <functional> #include <numeric> using namespace boost; using namespace std; class CObservable : boost::noncopyable { public: typedef boost::function<void(int)> Func; CObservable() : m_observerId(0) {} virtual ~CObservable(){} int Attach(const Func& f) { int k = m_observerId++; m_observers[k] = f; return k; } void Detach(int key) { m_observers.erase(key); } void Notify( int i ) { for ( auto it = m_observers.begin(); it != m_observers.end(); it++ ) { it->second(i); } } private: int m_observerId; std::map<int, Func> m_observers; }; struct stA { void print(int a) { cout << "stA=" << a << endl; } }; void print(int a) { cout << "print=" << a << endl; } int main(int argc, char **argv) { CObservable myObservable; myObservable.Attach(print); stA t; boost::function<void(int)> f = boost::bind(&stA::print, &t, _1); int key = myObservable.Attach(f); int a = 100; myObservable.Notify(a); myObservable.Detach(key); a = 999; myObservable.Notify(a); getchar(); return 0; }
以上是关于C++设计模式-Observer观察者模式的主要内容,如果未能解决你的问题,请参考以下文章