一個(gè)類只有一個(gè)實(shí)例
- 將所有構(gòu)造函數(shù)私有化,防止外部創(chuàng)建對(duì)象
- 給出共有靜態(tài)成員函數(shù)為獲取對(duì)象實(shí)例的唯一渠道
- 應(yīng)用場(chǎng)景:緩存,日志,工具類,配置,線程池等
分類:
餓漢式:程序啟動(dòng)就創(chuàng)建對(duì)象,不管用不用
懶漢式:需要用的時(shí)候創(chuàng)建,不用了銷毀
餓漢式
程序啟動(dòng)就創(chuàng)建對(duì)象實(shí)例,不管有沒有使用該對(duì)象
#include<iostream>
using namespace std;
//餓漢式 程序啟動(dòng)就創(chuàng)建對(duì)象實(shí)例,不管有沒有使用該對(duì)象
class single
{
int m_data;
//1. 把所有構(gòu)造函數(shù)私有
single(int data = 0) {}
single(single const& single1) {}
//2.靜態(tài)成員對(duì)象
static single s_single;
//3.提供靜態(tài)公有方法返回該私有靜態(tài)成員對(duì)象
public:
static single& getinstance()
{
return s_single;
}
};
single single::s_single(10);
int main()
{
single& s1 = single::getinstance();
single& s2 = single::getinstance();
cout << &s1 << " " << &s2 << endl;
return 0;
}
懶漢式
你需要用對(duì)象才創(chuàng)建該對(duì)象實(shí)例
#include<iostream>
using namespace std;
//懶漢式 你需要用對(duì)象才創(chuàng)建該對(duì)象實(shí)例
class singleton
{
int m_data;
//1. 把所有構(gòu)造函數(shù)私有
singleton(int data = 0) {}
singleton(singleton const& single1) {}
//2.靜態(tài)成員對(duì)象指針
static singleton* s_single;
//3.提供靜態(tài)公有方法返回該私有靜態(tài)成員對(duì)象
public:
static singleton& getinstance()
{
if (s_single == NULL)
{
s_single = new singleton(20);
}
return *s_single;
}
~singleton()
{
if (s_single)
delete s_single;
s_single = NULL;
}
};
singleton* singleton::s_single = NULL;
int main()
{
singleton& st1 = singleton::getinstance();
singleton& st2 = singleton::getinstance();
cout << &st1 << " " << &st2 << endl;
return 0;
}