首先定義一個模板類 Singleton
在Singleton.h中
#define DEFINE_SINGLETON2(class_name); \
public: \
friend class Singleton<class_name>;\
private: \
class_name(const class_name&){} \
class_name& operator=(const class_name&);
template< typename T > class Singleton
{
protected:
Singleton() {}
virtual ~Singleton() {}
Singleton(const Singleton< T >&) {}
Singleton< T >& operator = (const Singleton< T >&){}
class CGarbo //它的唯一工作就是在析構函數中刪除CSingleton的實例
{
public:
~CGarbo()
{
if(Singleton< T >::m_pInstance )
delete Singleton< T >::m_pInstance;
}
};
public:
static T& GetSingleton()
{
static T _singleton;
// if (m_pInstance == NULL)
// m_pInstance = new T();
return _singleton;
}
};
然後我們來實現自己的CLuaScriptMgr類
class CLuaScriptMgr : public Singleton<CLuaScriptMgr>
{
/*模板類Singleton爲CLuaScriptMgr的友元類,所以Singleton可以調用CLuaScriptMgr的私有方法*/
DEFINE_SINGLETON2(CLuaScriptMgr)
private:
CLuaScriptMgr();
~CLuaScriptMgr();
。。。
};
因爲CLuaScriptMgr的構造函數,拷貝構造函數,賦值函數都被定義爲 私有的。所以外部是沒辦法創建CLuaScriptMgr 對象的, 這裏把Singleton聲明爲CLuaScriptMgr的友元,只有在Singleton 可以訪問CLuaScriptMgr的所有方法。
在main.cpp中使用的話,直接聲明一個宏
#define g_LuaSingleton CLuaScriptMgr::GetSingleton()
調用的時候:
g_LuaSingleton.LoadScript("../../test/HelloWorld.lua");
這樣一個單例對象CLuaScriptMgr 就已經完成了。