懒汉模式
mutex m;
class Singleton
{
public:
static Singleton* getInstance() {
if (instance == nullptr) {
m.lock();
if (instance == nullptr) {
instance = new Singleton();
}
m.unlock();
}
return instance;
}
private:
Singleton();
~Singleton();
static Singleton *instance;
int i;
};
Singleton *Singleton::instance = nullptr;
饿汉模式
class Singleton {
private:
static Singleton *single;
Singleton();
~Singleton();
public:
static Singleton *getinstance();
};
Singleton *Singleton::single = new Singleton();
Singleton::Singleton()
{
}
Singleton::~Singleton()
{
}
Singleton* Singleton::getinstance() {
return single;
}