单例模式C++实现
编辑:谯胜平 分类:程序与算法 标签:单例模式 发布时间:2021-03-25 浏览次数:61次
1、饿汉式(在代码运行时就创建实例)
#include<iostream> using namespace std; class Singleton{ private: static Singleton *pInstance; Singleton(){ cout << "build" << endl; }; public: static Singleton* getInstance(){ return pInstance; } }; //实例化 Singleton* Singleton::pInstance = new Singleton(); int main(){ Singleton *s1 = Singleton::getInstance(); Singleton *s2 = Singleton::getInstance(); cout << s1 << endl; cout << s2 << endl; return 0; }
程序运行结果:
2、懒汉式(在需要用到实例时才进行初始化,单线程)
#include<iostream> using namespace std; class Singleton{ private: static Singleton *pInstance; Singleton(){ cout << "build" << endl; }; public: static Singleton *getInstance(){ if(pInstance == nullptr){ pInstance = new Singleton(); } return pInstance; } }; Singleton* Singleton::pInstance = nullptr; int main(){ Singleton *s1 = Singleton::getInstance(); Singleton *s2 = Singleton::getInstance(); cout << s1 << endl; cout << s2 << endl; return 0; }
程序运行结果:
3、懒汉式(在需要用到实例时才进行初始化, 多线程)
#include<iostream> #include<thread> #include<mutex> using namespace std; mutex mt; class Singleton{ private: static Singleton* pInstance; Singleton(){ cout << "build" << endl; } Singleton(const Singleton& ref){}; Singleton& operator=(const Singleton&){}; public: static Singleton* getInstance(){ if(pInstance == nullptr){ mt.lock(); if(pInstance == nullptr){ pInstance = new Singleton(); } mt.unlock(); } return pInstance; } }; Singleton* Singleton::pInstance = nullptr; void func(){ Singleton* s1 = Singleton::getInstance(); cout << s1 <<endl; } int main(){ thread t1(func); thread t2(func); t1.join(); t2.join(); return 0; }
程序运行结果: