单例模式
来源:互联网 发布:js写酷炫的界面 编辑:程序博客网 时间:2024/06/03 13:40
/****单例模式要点:一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。***/#include <iostream>using namespace std;class CSingleton{ public: static CSingleton * GetInstance() { if(NULL == m_pInstance) m_pInstance = new CSingleton(); return m_pInstance; } static void Release() //必须,否则会导致内存泄露 { if(NULL != m_pInstance) { delete m_pInstance; cout<<"this is CSingleton::Release()"<<endl; m_pInstance = NULL; } } protected: CSingleton() { cout<<"CSingleton"<<endl; }; static CSingleton * m_pInstance;};CSingleton* CSingleton::m_pInstance = NULL;/***class CSingleDraw:public CSingleton{public: static CSingleDraw* GetInstance() { if(NULL == m_pInstance) m_pInstance = new CSingleDraw(); return (CSingleDraw*)m_pInstance; }protected: CSingleDraw() { cout<<"CSingleDraw"<<endl; }};***/int main(){ // CSingleDraw* s1 = CSingleDraw::GetInstance(); // CSingleDraw* s2 = CSingleDraw::GetInstance(); CSingleton *s1=CSingleton::GetInstance(); CSingleton *s2=CSingleton::GetInstance(); s2->Release(); //this is CSingleton::Release() s1->Release(); return 0;}