c++单例模式
单例是设计模式里面的一种,全局有且只有一个类的 static 实
例,在程序任何地方都能够调用到。
单例模式的几种方式
1. 懒汉式
2. 饿汉模式
class singleton
{
protected:
singleton(){}
private:
static singleton* p;
public:
static singleton* instance()
{
if (p == nullptr)
p = new singleton();
return p;
}
};
singleton* singleton :: p = nullptr;
class singleton
{
protected:
singleton(){}
private:
static singleton *p;
public:
static singleton* instance()
{
return p;
}
};
singleton* singleton::p = new singleton();