C++ 實現一個單例模式

// ConsoleTest.cpp : 定義控制檯應用程序的入口點。
//

#include <iostream>
using namespace std;
class CSingleton
{
public:
static CSingleton* getInstance() //一個靜態函數,獲取累對象
{
if (NULL == m_pSingleton)
{
m_pSingleton = new CSingleton();
}
return m_pSingleton;
}
static void cleanInstance(){delete m_pSingleton;} //刪除實例
int getValue(){return m_iValue;} //獲取值
void setValue(int iValue){m_iValue = iValue;} //設置值
private:
int m_iValue; //私有變量               
static CSingleton* m_pSingleton; //一個私有的靜態指針
CSingleton() { cout << "構造函數" << endl; }
~CSingleton() { cout << "析構函數" << endl; }
};

CSingleton* CSingleton::m_pSingleton = NULL;
int main()
{
CSingleton* pSingleton1 = CSingleton::getInstance();//靜態函數只能用雙冒號調用
CSingleton* pSingleton2 = CSingleton::getInstance();

pSingleton1->setValue(123);
int n1 = pSingleton1->getValue();
pSingleton2->setValue(124);
int n2 = pSingleton2->getValue();
int n3 = pSingleton1->getValue();


if (pSingleton1->getValue() == pSingleton2->getValue())
{
cout << "同一個實例" << endl;
}
else
{
cout << "不同的實例" << endl;
}

CSingleton::cleanInstance();
return 0;

 }



//運行結果如下圖


 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章