1、懒汉模式
#include <iostream>
#include <mutex>
using namespace std;
class Instance {
private: static Instance* instance;
private: Instance() { cout << " 创建对象" <<endl; }
private: static mutex* locker;
public: static Instance* getInstance() {
if (instance == NULL) {
locker->lock();
if (instance == NULL) {
instance = new Instance();
}
locker->unlock();
}
return instance;
}
};
Instance* Instance::instance = nullptr;
mutex* Instance::locker = nullptr;
int main()
{
Instance* a = Instance::getInstance();
Instance* b = Instance::getInstance();
return 0;
}
结果:
gzx@gzx:~/Mytest$ g++ Single_Instance_lan.cpp -o test
gzx@gzx:~/Mytest$ ./test
创建对象
2、饿汉模式
#include <iostream>
#include <mutex>
using namespace std;
class Instance {
private: static Instance* instance;
private: Instance() { cout << " 创建对象" <<endl; }
public: static Instance* getInstance() {
return instance;
}
};
Instance* Instance::instance = new Instance();
int main()
{
Instance* a = Instance::getInstance();
Instance* b = Instance::getInstance();
return 0;
}
结果:
gzx@gzx:~/Mytest$ g++ Single_Instance_e.cpp -o test
gzx@gzx:~/Mytest$ ./test
创建对象