[C++] 单例模型 →→→→→进入此内容的聊天室

来自 , 2019-11-26, 写在 C++, 查看 160 次.
URL http://www.code666.cn/view/d77f0076
  1. #ifndef SINGLETON_H
  2. #define SINGLETON_H
  3.  
  4. #include "synobj.h"
  5.  
  6. class Singleton {
  7. public:
  8.     static Singleton& Instance() { // Unique point of access
  9.         Lock lock(_mutex);
  10.         if (0 == _instance) {
  11.             _instance = new Singleton();
  12.             atexit(Destroy); // Register Destroy function
  13.         }
  14.         return *_instance;
  15.     }
  16.     void DoSomething(){}
  17. private:
  18.     static void Destroy() { // Destroy the only instance
  19.         if ( _instance != 0 ) {
  20.             delete _instance;
  21.             _instance = 0;
  22.         }
  23.     }
  24.     Singleton(){} // Prevent clients from creating a new Singleton
  25.     ~Singleton(){} // Prevent clients from deleting a Singleton
  26.     Singleton(const Singleton&); // Prevent clients from copying a Singleton
  27.     Singleton& operator=(const Singleton&);
  28. private:
  29.     static Mutex _mutex;
  30.     static Singleton *_instance; // The one and only instance
  31. };
  32.  
  33. #endif/*SINGLETON_H*/

回复 "单例模型"

这儿你可以回复上面这条便签

captcha