The Singleton mode is a simple design mode that generates only one specific object and is generally used for global variables to ensure that the variables used by the entire system are unique.
In Singleton mode, constructor and destructor are generally set to private, and static functions are used for acquisition and release.
Specific instance:
Singleinstance. H Content
1 #ifndef SingleInstance_H_H 2 #define SingleInstance_H_H 3 4 #include <iostream> 5 using namespace std; 6 7 class SingleInstance 8 { 9 public:10 static SingleInstance* getInstance(){11 if(instance == NULL){12 instance = new SingleInstance();13 }14 return instance;15 }16 17 static void release(){18 if(instance != NULL){19 delete instance;20 instance = NULL;21 }22 }23 24 private:25 SingleInstance() {}26 ~SingleInstance() {}27 static SingleInstance *instance;28 };29 30 SingleInstance* SingleInstance::instance = NULL;31 32 33 void SingleInstanceTest()34 {35 SingleInstance *instance1 = SingleInstance::getInstance();36 SingleInstance *instance2 = SingleInstance::getInstance();37 if(instance1 == instance2){38 cout << "The tow instances is the same!" << endl;39 }40 else{41 cout << "The tow instances is different!" << endl;42 }43 SingleInstance::release();44 }45 46 #endif
Because the created object is the same, the release () function can be called once.
Design Mode 3-singleton Mode