0x01 concept
The initial definition of the singleton pattern appears in design mode (Eddisonvis):"guarantees that a class has only one instance and provides a global access point to access it." ”
The implementation of the Singleton pattern: the constructor is declared as private or protect to prevent being instantiated by an external function, and a private static class pointer is saved as a unique instance, and the construction of the instance is a static statically class method of public. The method returns an instance of the Singleton class that is unique.
0x02 Implementation method
1. Lazy Mode (critical section for thread safety)
It's not going to instantiate a class unless it's a last resort, which means that it will be instantiated the first time the class instance is used, which is a lazy implementation.
due to thread synchronization, the More traffic is available, or the number of threads that may be accessed is much larger, with a hungry man implementations for better performance. It is time to change space.
Class singleton{protected: Singleton () {initializecriticalsection (&criticalsection);//Initialize critical section } ~singleton () {deletecriticalsection (&criticalsection); Destroy Critical Zone }private: static singleton* p;public: critical_section criticalsection;//Critical Zone static singleton* initance ();}; pthread_mutex_t singleton::mutex;singleton* Singleton::p = null;singleton* singleton::initance () { if (p = = NULL) c11/>{ entercriticalsection (&criticalsection); Enter the critical section if (p = = NULL) p = new Singleton (); LeaveCriticalSection (&criticalsection); } return p;}
Lazy implementations of internal static variables:
Class singleton{protected: Singleton () { pthread_mutex_init (&mutex); } Public: static pthread_mutex_t mutex; Static singleton* initance (); int A;}; pthread_mutex_t singleton::mutex;singleton* singleton::initance () { pthread_mutex_lock (&mutex); static Singleton obj; Pthread_mutex_unlock (&mutex); return &obj;}
2. A hungry man mode (itself satisfies multithreading security)
A hungry man, in the case of a singleton class definition, is instantiated.
When the traffic is small, the use of lazy to achieve. It is time to change space.
Class singleton{protected: Singleton () {}private: static singleton* p;public: static singleton* Initance ();}; singleton* Singleton::p = new singleton;singleton* singleton::initance () { return p;}
Singleton Mode C + +