单例模式
单例模式很明显,就是只能存在一个实例。所以随之想到的就是将类的构造函数变成私有函数,这样外界就无法创建实例对象。那么应该在什么时候生成实例对象呢?此时就分成了单例模式的两种不同方案。
饿汉模式
可以把一个类想象成一家蛋糕店,饿汉很饿,所以进蛋糕店时就要立刻消费,买东西吃。所以,饿汉模式在类创建时就生成了对象。
#includeusing namespace std; class Singleton { private: Singleton() { cout << "构造函数私有化" << endl; } static Singleton* m_instance;//唯一实例对象 public: static Singleton* getinstance() { if (m_instance == NULL) { m_instance = new Singleton(); } return m_instance; } }; Singleton* Singleton::m_instance = new Singleton(); int main() { Singleton* s1 = Singleton::getinstance(); Singleton* s2 = Singleton::getinstance(); if (s1 = s2) { cout << "相同对象" << endl; } else { cout << "不同对象" << endl; } return 0; }
懒汉模式
在使用对象时才初始化,只需要将全局变量中一开始初始化为空指针。这样就会在调用GetInstance时进行new一个对象
Singleton* Singleton::m_instance = nullptr;



