Discussion on the singleton mode of C ++ Design Mode
Singleton mode: ensures that a class has only one instance and provides a global access point to access it.
Generally, we can make a global variable to make an object accessible, but it cannot prevent customers from instantiating multiple objects. The best way is to let the class itself protect its unique instance, this class can ensure that no other instance can be created, and it can provide a method to access the instance.
Singleton encapsulates its unique instance, so that it can strictly control how the customer accesses it and when to access it. Simply put, it is controlled access to the unique instance.
Implementation principle: privatize the constructor by providing only one 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 the static method or static attribute
Of course, when multiple threads are used for an object, multiple instances may be created, and the object creation process can be locked.
- class Singleton{
- public:
- static Singleton* Instance();
- protected:
- Singleton(){}
- Singleton(const Singleton &instance){}
- Singleton& operator=(const Singleton &instance){}
- private:
- static Singleton* instance;
- };
- Singleton* Singleton::Instance(){
- if(instance == 0)
- instance = new Singleton;
- return instance;
- }
- Singleton* Singleton::instance = 0;
In fact, the most important thing in the singleton mode is to privatize the public constructor. In this way, the constructor's instantiation right is handed over to the class itself, so that Singleton can control the class instantiation. Of course, in addition to constructors, we also need to privatize the class control replication function copy constructor and value assignment operation. Because the client has no right to construct, there is no right to control the replication function.