Singleton mode is to ensure that a class has only one instance and is easy to access outside. So generally only the constructor, copy function, destructor, assignment function, variable name into private. You can then use a Get function to access the provided interface. Consider thread safety and lock it up.
First, lazy mode:
1. Lazy mode for static member instances:
Class Singleton{private: static singleton* m_instance; Singleton () {}public: static singleton* getinstance ();}; singleton* singleton::getinstance () { if (NULL = = m_instance) { Lock (); if (m_instance = = NULL) { m_instance = new Singleton; } UnLock (); } return m_instance;}
2. Lazy mode of internal static instance
Class Singletoninside{private: singletoninside () {}public: static singletoninside* getinstance () { Lock (); static Singletoninside instance; UnLock (); return instance;} ;
Second, a hungry man mode
Static instance initialization is initiated by the main thread in a single-threaded manner before the program starts to enter the main function, without worrying about multithreading issues. This mode should be used to avoid frequent lock contention when performance requirements are high.
Class Singletonstatic{private: static const singletonstatic* m_instance; Singletonstatic () {}public: static const singletonstatic* getinstance () { return m_instance; }};
Thread-Safe single-case mode