先上代码:
#include <iostream>
using namespace std;
class Singleton
{
private:
int test;
Singleton() { cout << "new" <<endl; test = 0; }
~Singleton() { cout << "delete" << endl; }
public:
static Singleton *GetInstance()
{
static Singleton singleton;
return &singleton;
}
void SetValue(int v) { test = v; }
int GetValue() { return test; }
};
int main()
{
Singleton *single1 = Singleton::GetInstance();
Singleton *single2 = Singleton::GetInstance();
cout << "value 1: " << single1->GetValue() << endl;
single1->SetValue(100);
cout << "value 2: " << single2->GetValue() << endl;
if( single2 == single1 )
cout << "single1 and single2 is the same object." << endl;
return 0;
}
C++单例模式的实现方式有很多种,这种是我最喜欢的,它有以下优点:
1:能正确完成单例这个目标(废话)。
2:能在适当的时候自动运行构造和析构函数。
3:能够很轻易解决线程同步的问题(在GetInstance,SetValue,GetValue等函数运行时加锁就行了)