/*** @ Template name: MMSCMibSingleton * @ intro: singleton pattern * @ notes: MMSCMibSingleton must be set as a friend class for all classes that inherit the template, and set its own constructor to private */template <typename type> class MMSCMibSingleton {public:/*** get the global sole instance object. if it is null, create it. */static type * GetInstance () {// double judgment to avoid the following coincidence: // when one thread is judging, another thread is still being created, when this thread starts to obtain the lock, another thread is created and left. In this case, the bug is difficult to diagnose, but it exists, especially in the case of high concurrency. If (NULL = m_instance) {pthread_mutex_lock (& m_mutex); if (NULL = m_instance) {m_instance = new type ();} pthread_mutex_unlock (& m_mutex );} return m_instance;}/*** distory the global sole instance object. */static void Destroy () {pthread_mutex_lock (& m_mutex); // you do not need to perform a double check here, because delete null does not cause a bug. if (NULL! = M_instance) {delete m_instance; m_instance = NULL;} pthread_mutex_unlock (& m_mutex);} protected:/*** constructor */MMSCMibSingleton () {pthread_mutex_init (& m_mutex, NULL);}/*** destructor */~ MMSCMibSingleton () {pthread_mutex_destory (& m_mutex);} private: static type * m_instance; pthread_mutex_t m_mutex ;};
Example:
class SubClass:public MMSCMibSingleton<SubClass>{private: SubClass(){};friend MMSCMibSingleton<SubClass>;};SubClass* SubClass::m_instance = NULL;int main(){ SubClass* clss = SubClass::GetInstance(); //SubClass dsa;//wrong return 0;}
The implementation of C ++ Singleton is troublesome. You are welcome to provide your own solutions. The multi-thread lock is not required. However, it is necessary to implement Singleton without violating the seven principles of object-oriented design.