QtDesignPatterns/singletonpattern/singletonpattern.h

84 lines
1.3 KiB
C++

#include <iostream>
#include <mutex>
using namespace std;
//懒汉式
/*
class SingleObject
{
private:
SingleObject()
{
cout << "create SingleObject" << endl;
}
static SingleObject *instance;
public:
static SingleObject *getInstance()
{
if (instance == nullptr)
{
instance = new SingleObject();
}
return instance;
}
};
SingleObject *SingleObject::instance = nullptr;
*/
//饿汉式
/*
class SingleObject
{
private:
SingleObject()
{
cout << "create SingleObject" << endl;
}
public:
static SingleObject *getInstance()
{
static SingleObject instance;
return &instance;
}
}
*/
//多线程加锁
class SingleObject
{
private:
SingleObject()
{
cout << "create SingleObject" << endl;
}
static SingleObject *instance;
static mutex *my_mutext;
public:
static SingleObject *getInstance()
{
if(instance == nullptr)
{
my_mutext->lock();
instance = new SingleObject();
my_mutext->unlock();
}
return instance;
}
void test()
{
cout << "hello world" << endl;
}
};
SingleObject *SingleObject::instance = nullptr;
mutex *SingleObject::my_mutext = new mutex();