看一个hunspell应用库的时候发现的,虽然存在一点内存泄露问题,但是应付普通的开发足够了.
用法如下:
typedef Singleton<SpellCheck> SpellCheckS;
SpellCheck& sc = SpellCheckS::instance();
源代码如下:
#ifndef SINGLETON_H_
#define SINGLETON_H_
template <typename TYPE>
class Singleton
{
private:
Singleton<TYPE>() : _instance(0) {}
public:
/// Global access point to the Singleton.
static TYPE& instance(void)
{
Singleton<TYPE>& singleton = Singleton<TYPE>::instance_i();
if (singleton._instance == 0)
{
singleton._instance = new TYPE;
}
return *singleton._instance;
}
/// Explicitly delete the Singleton instance.
static void close(void)
{
Singleton<TYPE>& singleton = Singleton<TYPE>::instance_i();
if (singleton._instance)
{
delete singleton._instance;
}
}
protected:
/// Contained instance.
TYPE* _instance;
/// Get pointer to the Singleton instance.
static Singleton<TYPE> &instance_i (void)
{
static Singleton<TYPE> _singleton;
return _singleton;
}
};
#endif