3 CLuaScriptMgr单例设计

来源:互联网 发布:网络配线架怎么打 编辑:程序博客网 时间:2024/04/30 07:04

首先定义一个模板类 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 就已经完成了。




原创粉丝点击