QtDesignPatterns/singletonpattern/singletonpattern.h

84 lines
1.3 KiB
C
Raw Permalink Normal View History

2024-02-06 17:21:37 +08:00
#include <iostream>
#include <mutex>
using namespace std;
//<2F><><EFBFBD><EFBFBD>ʽ
/*
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;
*/
//<2F><><EFBFBD><EFBFBD>ʽ
/*
class SingleObject
{
private:
SingleObject()
{
cout << "create SingleObject" << endl;
}
public:
static SingleObject *getInstance()
{
static SingleObject instance;
return &instance;
}
}
*/
//<2F><><EFBFBD>̼߳<DFB3><CCBC><EFBFBD>
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();