Singleton mode is one of the creation modes. In our software development process, there are many classes that are only created once globally, such as app framework class, global management class, configuration file, log, database, etc. Using singleton mode can make our code elegant.
The UML class diagram and C++ sample code are given below:
// singleton.h
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
class CSingleton
{
private:
CSingleton() {}
~CSingleton() {}
static CSingleton* sm_pSingleton;
public:
static CSingleton* Instance();
static void ExitInstance();
public:
void Test() {printf("CSingleton::Test()\n");}
};
#endif // __SINGLETON_H__
// singleton.cpp
#include "Singleton.h"
CSingleton* CSingleton::sm_pSingleton = NULL;
CSingleton* CSingleton::Instance()
{
if (sm_pSingleton == NULL)
{
sm_pSingleton = new CSingleton;
}
return sm_pSingleton;
}
void CSingleton::ExitInstance()
{
if (sm_pSingleton)
{
delete sm_pSingleton;
sm_pSingleton = NULL;
}
}
// main.cpp
#include "Singleton.h"
int main(int argc, char* argv[])
{
CSingleton::Instance()->Test();
CSingleton::ExitInstance();
getchar();
return 0;
}
In addition, we can extend CSington to a template class, CSingleton<T>, to avoid duplicating the implementation of Instance and ExitInstance.
C/C++ macros can also simplify code
#ifndef SINGLETON_H
#define SINGLETON_H
#define DISABLE_COPY(Class) \
Class(const Class &) = delete; \
Class &operator=(const Class &) = delete;
#define SAFE_DELETE(p) {if (p) {delete (p); (p) = NULL;}}
#define DECLARE_SINGLETON(Class) \
public: \
static Class* instance(); \
static void exitInstance(); \
private: \
Class() {}; \
DISABLE_COPY(Class) \
static Class* s_pInstance;
#define IMPL_SINGLETON(Class) \
Class* Class::s_pInstance = NULL; \
Class* Class::instance(){ \
if (!s_pInstance){ \
s_pInstance = new Class; \
} \
return s_pInstance; \
} \
void Class::exitInstance(){ \
SAFE_DELETE(s_pInstance) \
}
#endif // SINGLETON_H
By using DECLARE_in a class header fileSINGLETON macro, using IMPL_in the implementation fileSINGLETON macro, we define this class as a single class.