單例設計模式
單例:整個項目中,有某個類或者某些特殊的類,屬于該類的對象只能建立一個。
#include<iostream>
using namespace std;class MyCAS
{
private:MyCAS(){}private:static MyCAS *m_instance;public:static MyCAS *GetInstance() ///得到對象的接口函數{if(m_instance==NULL){m_instance = new MyCAS();static CGarhuishou cl;}return m_instance;}void func(){cout << "test" << endl;}class CGarhuishou ///類中套類,釋放對象{public:~CGarhuishou(){if(m_instance!=NULL){delete MyCAS::m_instance;MyCAS::m_instance = NULL;}}};
};
MyCAS *MyCAS::m_instance = NULL;int main()
{MyCAS *p_a = MyCAS::GetInstance();p_a->func();return 0;
}
單例設計模式共享數據問題分析、解決
問題:需要在多個線程中創建單例類的對象,獲得對象的接口函數GetInstance()要互斥,否則會導致m_instance = new MyCAS()執行多次。
static MyCAS *GetInstance() ///得到對象的接口函數{if(m_instance==NULL) //提高效率,防止在創建對象后還需要一直加鎖。{std::unique_lock<std::mutex>mymutex(resource_mutex);if(m_instance==NULL){m_instance = new MyCAS();static CGarhuishou cl;}}return m_instance;}
std::call_one();
call_one功能:保證函數只執行一次
std::once_flag g_flag; ///系統定義的標記;
class MyCAS
{/*...*/static void CreateInstance() ///只需要執行一次的部分{m_instance = new MyCAS();static CGarhuishou cl;}static MyCAS *GetInstance() ///得到對象的接口函數{call_once(g_flag,CreateInstance); ///第一個參數是個標記,第二個參數是只要執行的函數return m_instance;}/*...*/
};