Singleton //OGRE: A 3D library for OpenGL and/or Direct3D

http://www.cppblog.com/sandy/archive/2005/11/30/1436.aspx

template 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 { public: void Use(); }; //初始化 //Root.cpp Root * Singleton::ms_Singleton =0; Root g_root;//must declare once only //使用 //Test.Cpp Root::getSingleton().Use(); 很简单,使用的技巧是template base class 这种实现方法的好处是复用性好。不过使用者要声明Root * Singleton::ms_Singleton =0;挺讨厌的 改进方法:template static member function 也就是改变声明一个static T*在template class,换成使用静态成员函数取出instance template 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() ); } };

你可能感兴趣的:(function,Class,library,Direct3D)