单例模式可以说是所有23种设计模式中最为简单的一个,没有之一。其主要思想就是保证整个应用环境中,最多只会有一个对象的实例。类关系图参考如下:
在c++中,单例模式的实现,较为常用的实现方式一般为:
1 namespace singleton 2 { 3 /************************************************************************** 4 * create : (jacc.kim) [5-17-2016] 5 * summary : 单例类 6 **************************************************************************/ 7 Singleton* Singleton::ms_Instance = nullptr; 8 class Singleton 9 { 10 public: 11 ~Singleton() {} 12 static Singleton* getInstance() { 13 if (nullptr == ms_Instance) { 14 ms_Instance = new (std::nothrow) Singleton(); 15 } 16 return ms_Instance; 17 } 18 19 static void freeInstance() { 20 if (nullptr != ms_Instance) { 21 delete ms_Instance; 22 ms_Instance = nullptr; 23 } 24 } 25 26 private: 27 Singleton() {} 28 Singleton(const Singleton&) = delete; 29 Singleton& operator=(const Singleton&) = delete; 30 31 static Singleton* ms_Instance; 32 33 };//class Singleton 34 35 }//namespace singleton