創建型模式----單例模式
單例模式指一個類只有一個實例,且該類能自行創建這個實例的一種模式;例如:windows中只能有一個任務管理器
模式結構和實現
通常情況下,普通類的構造函數是公有的,外部類可以通過"new 構造函數()"來生成多個實例,但是實現單例模式卻需要不同的操作方法
模式的結構
- 單例類:包含一個實例且能自行創建這個實例的類
- 訪問類:使用單例的類
實現單例模式的步驟
- 構造函數私有化
- 增加靜態私有的當前類的指針變量
- 提供靜態對外接口,讓用戶獲得單例對象
”餓漢式“和“懶漢式”
-
餓漢式創建單例模式:一開始就加載實例,用**”空間換時間“**,需要使用實例的時直接返回即可,無需創建
//餓漢式 class singleCase_hungry { private: singleCase_hungry() { cout << "餓漢式創建單例成功!" << endl; }; //私有構造函數 static singleCase_hungry *m_ptr; public: static singleCase_hungry* getInstance() { return new singleCase_hungry; } }; //外部調用方法 singleCase_hungry* singleCase_hungry::m_ptr = new singleCase_hungry;
餓漢式創建單例模式UML類圖
-
懶漢式創建單例模式:在使用實例時才被創建,用**”時間換空間“**
//懶漢式 class singleCase_lazy { private: singleCase_lazy() {}; //私有構造函數 static singleCase_lazy *m_ptr; public: static singleCase_lazy* getInstance() { if (m_ptr == NULL) m_ptr = new singleCase_lazy; return m_ptr; } void show() { cout << "懶漢式創建單例成功!" << endl; } }; //外部調用方法 singleCase_lazy* singleCase_lazy::m_ptr = NULL;
懶漢式創建單例模式UML類圖
單例模式實例
#include <iostream>
using namespace std;
//懶漢式
class singleCase_lazy {
private:
singleCase_lazy() {}; //私有構造函數
static singleCase_lazy *m_ptr;
public:
static singleCase_lazy* getInstance()
{
if (m_ptr == NULL)
m_ptr = new singleCase_lazy;
return m_ptr;
}
void show()
{
cout << "懶漢式創建單例成功!" << endl;
}
};
//餓漢式
class singleCase_hungry {
private:
singleCase_hungry() { cout << "餓漢式創建單例成功!" << endl; }; //私有構造函數
static singleCase_hungry *m_ptr;
public:
static singleCase_hungry* getInstance()
{
return new singleCase_hungry;
}
};
//外部調用方法
singleCase_lazy* singleCase_lazy::m_ptr = NULL;
singleCase_hungry* singleCase_hungry::m_ptr = new singleCase_hungry;
int main()
{
//main函數執行之前,餓漢式創建就已經完成
singleCase_lazy::getInstance()->show();
system("pause");
return 0;
}
需要注意的是,懶漢式創建單例模式是線程不安全的,需要配合鎖機制使用
餓漢式創建單例模式是線程安全的