Issues solved by singleton:
A class can only generate one object. Generally, if the system is composed of many parts, and each part only needs to be created once (one instance), or the project needs some globally shared data, the data can be encapsulated in a class, and only one object can be created for this class. (In actual projects, you may also need to consider data synchronization. This article does not consider this, solve only one problem at a time ).
Singleton implementation process:
1. constructor of the privatization class.
2. Add a static pointer to this class.
2. Add a static function (create a unique object of this class and assign the address of this object to a static pointer ).
Code implement
#include "stdafx.h"#include <iostream>#include <string>using namespace std;class Singleton{private: Singleton(){};public: static Singleton *m_pSingleton;public: static Singleton* Create() { if(NULL == m_pSingleton) m_pSingleton = new Singleton(); return m_pSingleton; }public: static void Delete() { if(NULL!= m_pSingleton) { delete m_pSingleton; m_pSingleton = NULL; } }public: string m_ObjectName;public: void SetObjectName(string name) { m_ObjectName = name; } string GetObjectName() { return m_ObjectName; }};Singleton* Singleton::m_pSingleton = NULL;int _tmain(int argc, _TCHAR* argv[]){ //Singleton object1; // Fail to create object Singleton *pObject1 = Singleton::Create (); string name =string("object1"); pObject1->SetObjectName(name); cout<<"Cur object name is : "<< pObject1->GetObjectName()<<endl;
Singleton *pObject2 = Singleton::Create (); cout<<"Cur object name is : "<< pObject2->GetObjectName()<<endl;
Pobject1-> Delete ();
Pobject2-> Delete ();
return 0;
}
Result:
Renark: This article does not consider data synchronization. Once Singleton is used, it needs to use kernel objects and other methods to synchronize data (in the case of multi-thread distribution ).
Only one problem is solved at a time.