c++ 观察者模式模板类
当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知依赖它的对象。观察者模式属于行为型模式。
使用c++11可变参数模板,实现通知函数参数可变。
#include <mutex>
#include <list>
#include <algorithm>
template <class TObserver>
class CSubject
{
public:
CSubject() {};
virtual ~CSubject() {};
bool Attach(TObserver* obj);
bool Detach(TObserver* obj);
public:
template <class FunctionPointer, class... Args>
void NotifyObservers(FunctionPointer fun, Args&&... args);
private:
std::list<TObserver*> list_observers;
std::mutex mutex;
};
template <class TObserver>
bool CSubject<TObserver>::Attach(TObserver* obj)
{
if (nullptr == obj)
{
return false;
}
std::unique_lock<std::mutex> locker(mutex);
auto it = std::find(list_observers.begin(), list_observers.end(), obj);
if (it == list_observers.end())
{
list_observers.push_back(obj);
}
return true;
}
template <class TObserver>
bool CSubject<TObserver>::Detach(TObserver* obj)
{
std::unique_lock<std::mutex> locker(mutex);
auto it = std::find(list_observers.begin(), list_observers.end(), obj);
if (it != list_observers.end())
{
list_observers.erase(it);
}
return true;
}
template <class TObserver>
template <class FunctionPointer, class... Args>
void CSubject<TObserver>::NotifyObservers(FunctionPointer fun, Args&&... args)
{
std::unique_lock<std::mutex> locker(mutex);
for (auto it : list_observers)
{
(it->*fun)(std::forward<Args>(args)...);
}
}

浙公网安备 33010602011771号