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;

 }



//运行结果如下图


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