The singleton pattern

The singleton pattern ensures that there is only one instance of a class, and that it instantiates itself and provides this instance singleton pattern to the entire system. The singleton pattern should only be used when there is a need for a true “single instance.”

class { public: protected: private: }a1; class Singleton { private: int i; static Singleton *instance; Singleton(int i) { this->i = i; } public: static Singleton *getInstance() { return instance; } void show() { cout << i << endl; }}; Singleton* Singleton::instance = new Singleton(8899); class A :public Singleton { }; int mainJ() { Singleton *s = Singleton::getInstance(); Singleton *s2 = A::getInstance(); cout << (s == s2) << endl; cin.get(); return 0; }Copy the code

advantages

Instance control

The singleton pattern prevents other objects from instantiating their own copy of a singleton, ensuring that all objects access a unique instance

flexibility

Because classes control the instantiation process, classes have the flexibility to change the instantiation process

disadvantages

overhead

Although the number is small, there is still some overhead if every time an object requests a reference it checks for the existence of an instance of the class. You can solve this problem with static initialization

Possible development confusion

When working with singleton objects, especially those defined in a class library, developers must remember that they cannot instantiate objects using the new keyword. Because the library source code may not be accessible, application developers may accidentally find themselves unable to instantiate this class directly.

Object lifetime

Cannot solve the problem of deleting a single object. In languages that provide memory management (such as based on. NETFramework language), and only a singleton class can cause an instance to be unallocated because it contains a private reference to that instance. In some languages (such as C++), other classes can remove object instances, but this results in dangling references in singleton classes