目的:限制类的实例个数只能是一个
例子:
#define AGT_DECLARE_SINGLETON(ClassName) public: static ClassName *Instance(); private: static ClassName *m_pInstance; #define AGT_DEFINE_SINGLETON(ClassName) ClassName *ClassName::m_pInstance = NULL; ClassName *ClassName::Instance() { if (NULL == m_pInstance) { m_pInstance = new ClassName; } return m_pInstance; }
class Manager { private: Manager() {} public: void show() { cout << "Success" << endl; } public: AGT_DECLARE_SINGLETON(Manager) //单例模式声明 }; AGT_DEFINE_SINGLETON(Manager); //函数实现
int main() { Manager* manager = Manager::Instance(); manager->show(); Manager* manager1 = Manager::Instance(); Manager* manager2 = Manager::Instance(); if(manager1 == manager2) { cout << "manager1 = manager2" << endl; } else { cout << "manager1 != manager2" << endl; } return 0; }