From bad78945ceba425f6a80e3b8dca2414d592970eb Mon Sep 17 00:00:00 2001 From: chai Date: Fri, 2 Aug 2019 20:51:00 +0800 Subject: =?UTF-8?q?*=E4=BF=AE=E6=94=B9=E6=96=87=E4=BB=B6=E5=90=8D=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- source/modules/asura-utils/Singleton.hpp | 59 ++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 source/modules/asura-utils/Singleton.hpp (limited to 'source/modules/asura-utils/Singleton.hpp') diff --git a/source/modules/asura-utils/Singleton.hpp b/source/modules/asura-utils/Singleton.hpp new file mode 100644 index 0000000..9bb7336 --- /dev/null +++ b/source/modules/asura-utils/Singleton.hpp @@ -0,0 +1,59 @@ +#ifndef _ASURA_SINGLETON_H_ +#define _ASURA_SINGLETON_H_ + +#include "UtilsConfig.h" + +namespace AsuraEngine +{ + + /// + /// 继承Singleton的类在第一次实例化时保存实例,之后如果再次实例化会报错。 + /// + template + class Singleton + { + public: + + static T* Get() + { + // 如果之前没有创建,在这里立即创建一个并保存 + if (!instance) instance = new T; + // 返回实例 + return instance; + } + + static void Destroy() + { + delete instance; + instance = nullptr; + } + + protected: + + Singleton() + { + // 如果有instance,意味着又创建了一个实例,这是错误的。 + ASSERT(!instance); + // 否则,将本实体作为实例 + instance = static_cast(this); + }; + + virtual ~Singleton() {}; + + static T* instance; + + private: + + Singleton(const Singleton& singleton); + + Singleton& operator = (const Singleton& singleton); + + }; + + // 实例初始化为空 + template + T* Singleton::instance = nullptr; + +} + +#endif // _ASURA_SINGLETON_H_ \ No newline at end of file -- cgit v1.1-26-g67d0