1. 程式人生 > >C++: 類單例的巨集實現(方便呼叫)

C++: 類單例的巨集實現(方便呼叫)

//===============Micros===============
//singletondeclare
#defineDECLARE_SHARE(ClassName)\
private:\
staticClassName*singleInstance;\
public:\
staticClassName*shareInstance()\
{\
if(NULL==singleInstance)singleInstance=newClassName();\
returnsingleInstance;\
}\
private:\
classCGarbo\
{\
public:\
~CGarbo()\
{if(ClassName::singleInstance)deleteClassName::singleInstance;}\
};\
staticCGarboGarbo;
//
#defineBUILD_SHARE(ClassName)\
ClassName*ClassName::singleInstance=NULL;
使用方式:
單例類標頭檔案中需要引用包含該巨集的標頭檔案,並在宣告中使用該巨集的 DECLARE_SHARE() 
而類實現中需要在一開始 BUILD_SHARE()
例:
//dlgmain.h
classDlgMain:publicQDialog
{
Q_OBJECT
DECLARE_SHARE(DlgMain)
public:
explicitDlgMain(QWidget*parent=0);
~DlgMain();
}
//dlgmain.cpp
#include"dlgmain.h"
BUILD_SHARE(DlgMain)
DlgMain::DlgMain(QWidget*parent):
QDialog(parent),
ui(newUi::DlgMain)
{
ui->setupUi(this);
...
}
...