题目:设计一个类,我们只生成该类的一个实例
只生成一个实例的类是实现了Singleton(单例)模式的类型。
解法一:只适用于单线程环境
因为只生成一个实例,所以把构造函数设为私有,以禁止他人创建实例。定义一个静态的实例,在需要的时候创建该实例。静态的介绍点击打开链接.
#include<iostream>
using namespace std;
class Singleton
{
public:
static Singleton* getinstance()
{
if (m_pinstance == NULL)//只有为空时才创建一个实例
m_pinstance = new Singleton();
return m_pinstance;
}
/*static void dinstance()
{
if (m_pinstance != NULL)
{
delete m_pinstance;
m_pinstance = NULL;
}
}*/
private:
Singleton() {};//构造函数定义为私有,确保只创建一个实例
static Singleton *m_pinstance;
};
Singleton* Singleton::m_pinstance = new Singleton();//实例Singleton初始化
void Test1() {
// 预期结果:两个实例指针指向的地址相同
Singleton* singletonObj1 = Singleton::getinstance();//引用静态成员的方式 <类名>::<静态成员名>
cout << singletonObj1 << endl;
Singleton* singletonObj2 = Singleton::getinstance();
cout << singletonObj2 << endl;
// Singleton::dinstance();
}
int main() {
Test1();
system("pause");
return 0;
}
解法二:
#include<iostream>
#include<thread>
#include<mutex>
#include<vector>
using namespace std;
class Singleton
{
private:
static mutex m_mutex;//互斥量
Singleton() {};
static Singleton* m_pinstance;
public:
static Singleton *getinstance()
{
if (m_pinstance == NULL)//两次判断
{
m_mutex.lock();
if (m_pinstance == NULL)
{
m_pinstance = new Singleton();
}
m_mutex.unlock();
}
return m_pinstance;
}
static void dinstance()
{
if (m_pinstance != NULL)
{
delete m_pinstance;
m_pinstance = NULL;
}
}
};
Singleton* Singleton::m_pinstance = NULL;
mutex Singleton::m_mutex;
void print()
{
Singleton* Singletonobj = Singleton::getinstance();
cout << Singletonobj << endl;
}
void test1()
{
vector<thread> threads;
for (int i = 0;i < 10;++i)
{
threads.push_back(thread(print));
}
for (auto& thr:threads) {
thr.join();
}
}
int main()
{
test1();
Singleton::dinstance();
system("pause");
return 0;
}
假设两个线程同时想创建一个实例。由于在同一时刻只有一个线程能得到同步锁,当第一个线程加上锁时,第二个线程只能等待
第一个线程发现还没创建实例时,创建一个实例,然后第一个线程释放同步锁,第二个线程加上同步锁,由于第一个线程已建立实例第二个线程就不在建立。但这种方法非常耗时,因为每次建立实例的时候都会加上同步锁。而此方法只是当第一次没有创建实例时加锁,如果创建了就不加锁。
参考文献:
(1)剑指offer
(2)剑指offer 面试题2 Singleton模式 C++实现 - 优快云博客 https://blog.youkuaiyun.com/huhaijing/article/details/51756225