定义:顾名思义,确保一个类在任何情况下都只有一个实例。
#include<iostream>
using namespace std;
class SingletonDP
{
public:
static SingletonDP* GetInstance();
private:
SingletonDP()
{
cout << "Constructor" << endl;
};//构造函数私有
static SingletonDP* pSingleInst;
};
SingletonDP* SingletonDP::pSingleInst = nullptr;
SingletonDP* SingletonDP::GetInstance()
{
cout << "Return Instance By GetInstance()" << endl;
if (!pSingleInst)
pSingleInst = new SingletonDP();
return pSingleInst;
}
int main()
{
cout << "SingletonDPTest" << endl;
SingletonDP *pTemp1 = SingletonDP::GetInstance();
SingletonDP *pTemp2 = nullptr;
if (pTemp1) pTemp2 = pTemp1->GetInstance();
cout << "pTemp1 Address: " << pTemp1 << endl;
cout << "pTemp2 Address: " << pTemp2 << endl;
system("pause");
return 0;
}
从上述例子输出结果可以看出:1.在获取该类实例对象时才会走构造函数;2.两者地址相同满足单例模式。
但是,这种方式是线程不安全的,如果多个线程都第一次访问该类实例的时候,可能会创建多个实例。
?
#include<iostream>
#include<mutex>
using namespace std;
class SingletonDP
{
public:
static SingletonDP* GetInstance();
private:
SingletonDP()
{
cout << "Constructor" << endl;
};//构造函数私有
static SingletonDP* pSingleInst;
static mutex sMutex;
};
SingletonDP* SingletonDP::pSingleInst = nullptr;
mutex SingletonDP::sMutex;
SingletonDP* SingletonDP::GetInstance()
{
cout << "Return Instance By GetInstance()" << endl;
if (!pSingleInst)
{
sMutex.lock();
if(!pSingleInst)
pSingleInst = new SingletonDP();
sMutex.unlock();
}
return pSingleInst;
}
int main()
{
cout << "SingletonDPTest" << endl;
SingletonDP *pTemp1 = SingletonDP::GetInstance();
SingletonDP *pTemp2 = nullptr;
if (pTemp1) pTemp2 = pTemp1->GetInstance();
cout << "pTemp1 Address: " << pTemp1 << endl;
cout << "pTemp2 Address: " << pTemp2 << endl;
system("pause");
return 0;
}
如上述代码所示:在GetInstance()方法中通过Double Check解决线程不安全问题。(也可以通过在创建线程之前先实例化一个实例对象来解决该问题)
#include<iostream>
using namespace std;
class SingletonDP
{
public:
static SingletonDP* GetInstance()
{
static SingletonDP OnlyInstance;
return &OnlyInstance;
}
private:
SingletonDP()
{
cout << "Constructor" << endl;
};//构造函数私有
};
int main()
{
cout << "SingletonDPTest" << endl;
SingletonDP *pTemp1 = SingletonDP::GetInstance();
SingletonDP *pTemp2 = nullptr;
if (pTemp1) pTemp2 = pTemp1->GetInstance();
cout << "pTemp1 Address: " << pTemp1 << endl;
cout << "pTemp2 Address: " << pTemp2 << endl;
system("pause");
return 0;
}
?上述模式在类创建的同时就已经创建好一个静态对象,以后不会改变,是线程安全的。
|