c++设计模式——单例模式
单例模式 一个类只允许创建唯一的对象 禁止在类的外部创建对象:私有化构造函数:private或protected 类的内部维护唯一对象:静态成员变量 提供访问单例对象的方法:静态成员函数,返回在类内部唯一构造的实例 创建方式 饿汉式:单例对象无论用或不用,程序启动即创建。 懒汉式:单例对象在用的时候再创建,不用即销毁。 一: #include <iostream> using namespace std; class Singleton { public: static Singleton *GetInstance() { if (m_Instance == NULL ) { m_Instance = new Singleton (); } return m_Instance; } static void DestoryInstance() { if (m_Instance != NULL ) { delete m_Instance; m_Instance = NULL ; } } // This is just a operation example int GetTest() { return m_Test; } private: Singleton() { m_Test = 10; } static Singleton *m_Instance; int m_Test; };