Singleton模式

来源:互联网 发布:鹏为crm软件 编辑:程序博客网 时间:2024/06/16 03:38

当有时候需要一个类只能有一个实例化对象的时候,可以考虑单例模式(Sigleton模式)

原理:用一个特殊方法来实例化所需要的对象。

实现方式:将构造函数,赋值,拷贝构造都设为私有,设置一个私有静态对象成员变量,只留出一个静态的接口获取这个唯一的实例。

c++代码如下

#include<iostream>//#include<mutex>using namespace std;class Singleton{private:static Singleton *m_pInstance;Singleton()   //构造函数是私有的  {}//禁用拷贝Singleton(const Singleton &);Singleton & operator = (const Singleton &);public:static Singleton * GetInstance(){if (m_pInstance == NULL)m_pInstance = new Singleton;return m_pInstance;}void func() { cout << "Singleton里的某个函数" << endl; }};Singleton * Singleton::m_pInstance = NULL;int main(){Singleton::GetInstance()->func();system("pause");}

但是这只适用于单线程下的程序,既然单例,就应该使一个对象改变时,其他所有对象都能看到。如果在多线程下,可能两个线程都进行到判断实例是否存在那一步,且此时唯一实例的确是NULL,此时两个线程都会执行new操作,这样将可能引发状态不一致的问题。

所以就有了Double-Checked Locking模式,即在判断NULL之后加一个异步的锁,以确保只执行一次


代码如下:

#include<iostream>#include<mutex>#include<thread>using namespace std;class Singleton{private://禁用拷贝,赋值运算之类Singleton(){}Singleton(const Singleton &);Singleton & operator = (const Singleton &);static Singleton *m_pInstance;static std::once_flag m_flag;public:static Singleton * GetInstance(){if (m_pInstance == NULL){std::call_once(m_flag, []() {m_pInstance = new Singleton;cout << "实例化完成" << endl;});}return m_pInstance;}void func() { cout << "Singleton里的某个函数" << endl; }};Singleton * Singleton::m_pInstance = NULL;std::once_flag Singleton::m_flag;int main(){Singleton::GetInstance()->func();system("pause");}
注:c++11中会保证静态成员变量的初始化时线程安全的,所以如果支持c++11,不加锁也没关系。其实我这边用的call_once也是c++11里的。。