Singleton mode: guarantees that a class has only one instance and provides a global access point to access it.
Usually we can let a global variable make an object accessible, but it does not prevent the client from instantiating multiple objects, one of the best way is to let the class itself is responsible for protecting its unique instance, this class can guarantee that no other instance can be created, and it can provide a way to access the instance.
Singleton mode because the Singleton class encapsulates its only instance, it can tightly control how the client accesses it and when it accesses it, simply as controlled access to the unique instance.
Implementation principle: Privatize the constructor, providing only a static method to create an object.
(1) Set the constructor to private;
(2) Declare a static field, initialize an instance, and return the Singleton object;
(3) Return the unique instance using a static or static property
Of course, when the object is multi-threaded, it may cause multiple instances to be created, and the process of creating the object can be locked.
- Singleton: Define a instance action
classsingleton{ Public: Staticsingleton*Instance ();protected: Singleton () {} Singleton (const Singleton&instance) {} singleton&operator= (Const Singleton &instance) {}Private: Staticsingleton*instance;}; Singleton*singleton::instance () {if(Instance = =0) Instance=NewSingleton; returninstance;} Singleton* Singleton::instance =0;
In fact, the most important thing in a singleton model is to privatize the public's constructor function. This gives the class itself the right to instantiate the constructed object, allowing Singleton to control the instantiation of the class. Of course, in addition to the constructor, you also need to privatize the class's control copy function (copy constructor, assignment operation) because the client does not have the right to construct, so there is no right to use the control copy function.
All rights reserved, welcome reprint, reprint please indicate source!
A simple example of C + + design mode