From 1497dccd63a84b7ee2b229b1ad9c5c02718f2a78 Mon Sep 17 00:00:00 2001 From: chai Date: Tue, 19 Mar 2019 23:06:27 +0800 Subject: *rename --- source/libs/asura-lib-core/singleton.hpp | 59 ++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 source/libs/asura-lib-core/singleton.hpp (limited to 'source/libs/asura-lib-core/singleton.hpp') diff --git a/source/libs/asura-lib-core/singleton.hpp b/source/libs/asura-lib-core/singleton.hpp new file mode 100644 index 0000000..756209a --- /dev/null +++ b/source/libs/asura-lib-core/singleton.hpp @@ -0,0 +1,59 @@ +#ifndef __ASURA_SINGLETON_H__ +#define __ASURA_SINGLETON_H__ + +#include "Config.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