- 因为在设计或开发中,肯定会有这么一种情况,一个类只能有一个对象被创建,如果有多个对象的话,可能会导致状态的混乱和不一致。这种情况下,单例模式是最恰当的解决办法。它有很多种实现方式,各自的特性不相同,使用的情形也不相同。今天要实现的是常用的三种,分别是饿汉式、懒汉式和多线程式。
- 通过单例模式, 可以做到:
- 1.确保一个类只有一个实例被建立
- 2.提供了一个对对象的全局访问指针
- 3.在不影响单例类的客户端的情况下允许将来有多个实例
例程:
#include <QCoreApplication>
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
once_flag g_flag;
class MyCAS{
private:
MyCAS()
{
}
private:
static MyCAS *m_instance;
static std::mutex my_mutex;
public:
static MyCAS *getInstance()
{
if(m_instance==nullptr)
{
std::unique_lock<std::mutex> ulock(my_mutex);
if(m_instance==nullptr)
{
m_instance=new MyCAS();
static garbageCollection garbage_collection;
}
}
return m_instance;
}
static MyCAS *getInstance2()
{
std::call_once(g_flag,createInstance);
return m_instance;
}
class garbageCollection
{
public:
~garbageCollection()
{
if(MyCAS::m_instance)
{
delete MyCAS::m_instance;
MyCAS::m_instance=nullptr;
}
}
};
public:
static void createInstance()
{
m_instance=new MyCAS();
cout<<"createInstance is working! "<<endl;
static garbageCollection garbage_collection;
}
void test()
{
cout<<"测试\n";
}
};
void myThread(int num)
{
cout<<"Thread "<<num<<" is begining!\n";
MyCAS *p_a=MyCAS::getInstance2();
cout<<"Thread "<<num<<" is over!\n";
}
MyCAS *MyCAS::m_instance=nullptr;
int main(int argc, char *argv[])
{
thread thread1(myThread,1);
thread thread2(myThread,2);
thread1.join();
thread2.join();
return 0;
}