Posted on 2008-04-18 18:14
RichardHe 阅读(184)
评论(2) 编辑 收藏 引用
了解了通过模板来使用单件模式
*.h
template <typename T> class CEGUIEXPORT Singleton
{
protected:
static T* ms_Singleton;
public:
Singleton( void )
{
assert( !ms_Singleton );
ms_Singleton = static_cast<T*>(this);//这个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 ); }
};
使用如下
class MyClass :public Singleton<MyClass>
{
public:
void run();
};
*.cpp
template MyClass* Singleton<MyClass>::ms_Singleton = NULL; ///注意,这里是Singleton构造函数.不是getSingleton方法
//好像也可以用 template<typename T> T* Singleton<T>::ms_Singleton = NULL;
//在使用它之前new一个对象
new MyClass();
MyClass::getSingleton().run();
在CEGUI中为什么不设计如下呢??????????????????????????????
emplate <class T> class Singleton
{
protected:
Singleton(){}
public:
static T& Instance()
{
static T instance;
return instance;
}
};
// Concrete singleton class, derived from Singleton<T>
class ExampleSingleton: public Singleton<ExampleSingleton>
{
// so that Singleton<ExampleSingleton> can access the
// protected constructor
friend class Singleton<ExampleSingleton>;
protected:
ExampleSingleton(){}
public:
// This class's real functionalities
void Write(){printf("Hello, World!");}
};
// use this singleton class
ExampleSingleton::Instance().Write();