Posted on 2005-11-30 11:38
小明 阅读(2421)
评论(1) 编辑 收藏 引用 所属分类:
C/C++ 、
Game Development
www.ogre3d.org
OGRE: A 3D library for OpenGL and/or Direct3D
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();
很简单,使用的技巧是template base class
这种实现方法的好处是复用性好。
不过使用者要声明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() ); }
};