Design Mode: Singleton Mode
Design Mode: Singleton Mode
Preface
The Singleton mode is a common software design mode. Its core structure only contains a special class called Singleton class. The Singleton mode ensures that there is only one instance in a class in the system and the instance is easy to access, so as to conveniently control the number of instances and save system resources. If you want to have only one class object in the system, the singleton mode is the best solution. (Baidu encyclopedia)
Body
We simply implement a singleton mode, first read the code, and then analyze:
Singleton sample code
# Include
Using namespace std; // Singleton mode class Single {private: static Single * instance; // constructor privatize Single () = default; public: // provides a static method to obtain the instance static Single * getInstance () {if (instance = nullptr) instance = new Single; return instance ;} // other data and function members are omitted}; Single * Single: instance = nullptr; // class D public inheritance Singleclass D: public Single {}; int main (void) {cout <******** Singleton mode ***** by David ***** <endl; Single * p1 = Single: getInstance (); single * p2 = Single: getInstance (); cout <(void *) p1 <ends <(void *) p2 <endl; delete p1; single * p3 = D: getInstance (); cout <(void *) p3 <endl; cin. get (); return 0 ;}
Run
From the running results, p1, p2, and p3 all point to the same object. P1 and p2 indicate the existence of the Singleton, while p3 indicates that there is only one Singleton in the inheritance system.
Design Principle of Singleton
To prevent users from creating class objects on their own, you need to set the constructor to private or protected. At the same time, the constructor must be private to prevent sub-classes from using constructor. Design a static class type pointer because there is only one static member in the entire inheritance system. Provides a static public method, which is an interface for obtaining a single instance externally.
In cocos2dx, there is a singleton. For example, we often use Director: getInstance (); to obtain the singleton for controlling the entire game.