0、核心要素
// 構(gòu)造、析構(gòu)函數(shù)私有化(一個進程只允許一個對象存在)
// 對象私有化、靜態(tài)化(因為接口靜態(tài)函數(shù))
// 對象調(diào)用接口靜態(tài)化(因為靜態(tài)函數(shù)脫離了類對象,可以直接調(diào)用)
一、懶漢
唯一的對象在使用時才進行初始化。存在多線程問題。文章來源:http://www.zghlxwxcb.cn/news/detail-653600.html
#include <iostream>
using namespace std;
class singleMode {
public:
static singleMode* getInstance() {
if (obj==nullptr) {
obj = new singleMode();
}
return obj;
}
void printMsg() {
cout << "print success." << endl;
}
private:
static singleMode* obj;
singleMode() {
cout << "instance create." << endl;
}
~singleMode() {
cout << "instance release." << endl;
}
};
singleMode* singleMode::obj = nullptr;
// singleMode* singleMode::obj = new singleMode();
int main()
{
{
singleMode::getInstance()->printMsg();
}
return 0;
}
二、餓漢
唯一的對象在定義時就完成初始化。文章來源地址http://www.zghlxwxcb.cn/news/detail-653600.html
#include <iostream>
using namespace std;
class singleMode {
public:
static singleMode* getInstance() {
/* if (obj==nullptr) {
obj = new singleMode();
}
*/
return obj;
}
void printMsg() {
cout << "print success." << endl;
}
private:
static singleMode* obj;
singleMode() {
cout << "instance create." << endl;
}
~singleMode() {
cout << "instance release." << endl;
}
};
// singleMode* singleMode::obj = nullptr;
singleMode* singleMode::obj = new singleMode();
int main()
{
{
singleMode::getInstance()->printMsg();
}
return 0;
}
到了這里,關(guān)于設計模式——經(jīng)典單例的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!