什么是單例模式:
在GOF的《設計模式:可復用面向?qū)ο筌浖幕A(chǔ)》中是這樣說的:保證一個類只有一個實例铸史,并提供一個訪問它的全局訪問點。
如何保證怯伊?
首先琳轿,需要保證一個類只有一個實例,那么就要在類中耿芹,要構(gòu)造一個實例利赋,就必須調(diào)用類的構(gòu)造函數(shù),如此猩系,為了防止在外部調(diào)用類的構(gòu)造函數(shù)而構(gòu)造實例,需要將構(gòu)造函數(shù)的訪問權(quán)限標記為protected或private中燥;
最后寇甸,需要提供要給全局訪問點,就需要在類中定義一個static函數(shù)疗涉,返回在類內(nèi)部唯一構(gòu)造的實例拿霉。
#include <iostream>
using namespace std;
class Singleton {
public:
static Singleton * getinstance() {
if (p == NULL) {
p = new Singleton();
}
else {
return p;
}
}
int gettest() {
return test;
}
void settest(int _t) {
test = _t;
}
private:
Singleton() { test = 0; }
static Singleton * p;
int test;
};
Singleton * Singleton::p = NULL;
int main() {
Singleton *p = Singleton::getinstance();
cout << p->gettest() << endl;
system("pause");
return 0;
}