What is a singleton mode?
Ensure that a class has only one instance and provides a global access point to access it. "DP"
Let the class itself be responsible for saving its only instance, which guarantees that no other instance can be created, and that the class can provide a way to access the instance. "DP"
When do I need a singleton mode?
The program requires only one method to control a feature and does not allow the creation of a second feature. For example: The number of the bank used to pick the machine.
Use singleton mode to understand the use of c++static keywords my blog post has made a brief analysis of static
Test Case:
[Code]int Main () { //Singleton Mode Initializes a method of two instances Singleton *s1 = Singleton::getinstance (); Singleton *s2 = Singleton::getinstance (); if (S1 = = s2) std::cout << "The objects is the same instance.\n"; else std::cout << "The objects is the different instance.\n"; return 0;}
Single-instance mode implementation:
[Code]class singleton{private: //Declare constructors as private, guaranteeing that only static objects within the class that use Singleton () {} //Declare a class (out-of-class initialization) are allowed The static Singleton *instance;public: //Statically member method provides a global access point that accesses only the instance. That is, provide an interface to create the object static singleton* getinstance () { if (instance! = NULL) { instance = new Singleton; } return instance; }};/ /class external initialization static member variable (static member variable must be initialized) singleton* singleton::instance = NULL;
Attached: If for multi-threaded programming case, need to lock and do two times to determine whether it is empty.
[Code]class singleton{private: //Declare constructors as private, guaranteeing that only static objects within the class that use Singleton () {} //Declare a class (out-of-class initialization) are allowed The static Singleton *instance;public: //Statically member method provides a global access point that accesses only the instance. That is, provide an interface to create the object static singleton* getinstance () { if (instance! = NULL) { Lock (syncobj) { if (instance! = NULL) { instance = new Singleton; } If }//lock }//if return instance; }};/ /class external initialization static member variable (static member variable must be initialized) singleton* singleton::instance = NULL;
Plus lock is for two threads with only one entry and another thread waiting. After the first thread enters and comes out, the latter can enter. The second one is to ensure that the first thread creates the instance, and the second thread enters and no longer creates the instance.
The above is the C + + design mode of simple knowledge of the content of a single case, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!