转自:http://www.cppblog.com/sandy/archive/2005/11/30/1436.html
template <typename T> class Singleton
{
protected:
static T* ms_Singleton;
public:
Singleton( void )
{
assert( !ms_Singleton );
ms_Singleton = static_cast< T* >( this );
}
~Singleton( void )
{ assert( ms_Singleton ); ms_Singleton = 0; }
static T& getSingleton( void )
{ assert( ms_Singleton ); return ( *ms_Singleton ); }
static T* getSingletonPtr( void )
{ return ( ms_Singleton ); }
};
//client端的代码
//Singleton的类
//Root.h
class Root:public Singleton<Root>
{
public:
void Use();
};
//初始化
//Root.cpp
Root * Singleton<Root>::ms_Singleton =0;
Root g_root;//must declare once only
//使用
//Test.Cpp
Root::getSingleton().Use();
{
protected:
static T* ms_Singleton;
public:
Singleton( void )
{
assert( !ms_Singleton );
ms_Singleton = static_cast< T* >( this );
}
~Singleton( void )
{ assert( ms_Singleton ); ms_Singleton = 0; }
static T& getSingleton( void )
{ assert( ms_Singleton ); return ( *ms_Singleton ); }
static T* getSingletonPtr( void )
{ return ( ms_Singleton ); }
};
//client端的代码
//Singleton的类
//Root.h
class Root:public Singleton<Root>
{
public:
void Use();
};
//初始化
//Root.cpp
Root * Singleton<Root>::ms_Singleton =0;
Root g_root;//must declare once only
//使用
//Test.Cpp
Root::getSingleton().Use();
很简单,使用的技巧是template base class
这种实现方法的好处是复用性好。
【分析:class Root:public Singleton<Root>之后,可以这样看Root,这个Root本质其实就是包含了
template <typename T> class Singleton
{...}
中的{...}大括号中的所有代码,别的什么也不是,不用考虑太复杂了,在此基础上就好理解了。
】
不过使用者要声明Root * Singleton<Root>::ms_Singleton =0;挺讨厌的
改进方法:template static member function
也就是改变声明一个static T*在template class,换成使用静态成员函数取出instance
template <typename T> class Singleton
{
private:
static T* & ms_Singleton()
{
static T* ms_Singleton_ =0 ;
return ms_Singleton_;
}
public:
Singleton( void )
{
assert( !ms_Singleton() );
ms_Singleton() = static_cast< T* >( this );
}
~Singleton( void )
{ assert( ms_Singleton() ); ms_Singleton() = 0; }
static T& getSingleton( void )
{ assert( ms_Singleton() ); return ( *ms_Singleton() ); }
static T* getSingletonPtr( void )
{ return ( ms_Singleton() ); }
};
{
private:
static T* & ms_Singleton()
{
static T* ms_Singleton_ =0 ;
return ms_Singleton_;
}
public:
Singleton( void )
{
assert( !ms_Singleton() );
ms_Singleton() = static_cast< T* >( this );
}
~Singleton( void )
{ assert( ms_Singleton() ); ms_Singleton() = 0; }
static T& getSingleton( void )
{ assert( ms_Singleton() ); return ( *ms_Singleton() ); }
static T* getSingletonPtr( void )
{ return ( ms_Singleton() ); }
};