Purpose: ensure that a class has only one instance and provides a global access point to it.
UML structure diagram:
Resolution:
The Singleton mode is actually a replacement policy for Global static variables. The two functions of the singleton mode mentioned above are implemented through the following mechanism in C ++: 1) There is only one instance, provides static member variables of a class. We all know that static member variables of a class are unique for all objects of a class. 2) provides a global access point to access it, that is, it provides the corresponding static member function to access this static member variable, which is unique for all objects of the class. in C ++, you can directly use the class domain to access the object without initializing a class.
The following implementation is actually a simple implementation of Singleton, which is not particularly common. Generally, if a project needs to use the singleton mode, generally, a singleton template class is implemented. The template parameters of the template class are classes in the singleton mode. For example:
Template <typename T> <br/> class Singleton <br/> {<br/> //. class declaration <br/>}; </P> <p> // class that requires the singleton mode <br/> class test <br/>: public Singleton <Test> <br/>{< br/> // class declaration <br/>}; <br/> however, the following implementation uses the simplest implementation method to demonstrate the role </P> <p> code: </P> <p> // Singleton. h <br/> # ifndef _ singleton_h _ <br/> # DEFINE _ singleton_h _ </P> <p> class Singleton <br/>{< br/> public: <br/> static Singleton * instance (); <br/> protected: <br/> singlet On (); <br/> PRIVATE: <br/> static Singleton * _ instance; <br/> }; </P> <p> # endif </P> <p> // Singleton. CPP <br/> # include "Singleton. H "<br/> # include <iostream> </P> <p> using namespace STD; </P> <p> Singleton * singleton: _ instance = 0; </P> <p> Singleton * singleton: instance () <br/> {<br/> If (_ instance = 0) <br/>{< br/> _ instance = new Singleton (); <br/>}< br/> else <br/> {<br/> cout <"There is one instance, you Can construct one more! "<Endl; <br/>}< br/> return _ instance; <br/>}</P> <p> singleton: Singleton () <br/>{< br/> cout <"constructing Singleton... "<Endl; <br/>}</P> <p> // main. CPP <br/> # include <iostream> <br/> # include "Singleton. H "</P> <p> using namespace STD; </P> <p> void main () <br/>{< br/> Singleton * SGN = singleton :: instance (); </P> <p >}</P> <p>
It should be noted that Singleton cannot be instantiated, So we declare its constructor as protected or directly declared as private.