作为C++设计模式中的单件模式归属于创建型模式之1,在软件设计进程中“出场“的机会还是很多,以下源码作为自己学习开源库代码时针对单件 模式做的1个总结,方便后期设计进程中的参考和学习。
#ifndef SINGLETON_HPP_
#define SINGLETON_HPP_
#include <boost/thread.hpp>
namespace ts
{
/**
*@breif
*@note base
*/
class CLocalStaticInstantiation
{
protected:
template <class T>
static void create(T*& ptr)
{
static T instance; // 静态局部变量
ptr = &instance;
}
};
/**
*@breif
*@note Helper class
*/
template <class T>
class CStaticInstantiationHelpler
{
// friend class
friend class CStaticInstantiation;
// holder
static T instance;
};
template <class T>
T CStaticInstantiationHelpler<T>::instance; // 静态全局变量[这是1个技能,否则单个对象没法随时初始化]
/**
*@breif
*@note support the static
*/
class CStaticInstantiation
{
protected:
template <class T>
static void create(T*& ptr)
{
ptr = &CStaticInstantiationHelpler<T>::instance;
}
};
template <class T>
class CDestroyer
{
T *doomed;
public:
CDestroyer(T* q):doomed(q)
{}
~CDestroyer();
};
template <class T>
CDestroyer<T>::~CDestroyer()
{
try
{
if (doomed)
{
delete doomed; // 在这里主要支持heap对象的反初始化
std::cout << "delete [ " << doomed << " ]" << std::endl;
}
}
catch (...){}
doomed = 0;
}
/**
*@breif
*@note support the dynamic alloctor
*/
class CLazyInstantiation
{
protected:
template <class T>
static void create(T*& ptr)
{
ptr = new T; // 支持运行时分配
static CDestroyer<T> destroyer(ptr); // 由static去进行删除
}
};
template <class T, class InstantiationPolicy=CLazyInstantiation>
class CSingleton : private InstantiationPolicy
{
public:
static T* instance();
};
template <class T, class InstantiationPolicy>
T* CSingleton<T, InstantiationPolicy>::instance()
{
static T* ptr = 0;
static boost::mutex m;
if ( !ptr )
{
boost::mutex::scoped_lock lock(m); // 支持多线程访问
if ( !ptr ) // 根据设计模式的设计思想来设计两次检查指针
{
InstantiationPolicy::create(ptr);
}
}
return const_cast<T*>(ptr);
}
}
#endif // SINGLETON_HPP_