/********************************************* 题目: 1)设计一个类,我们只能生成该类的一个实例 2)设计一个类,只能生成该类的3个实例 ******************************************/ //1) #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; m_pInstance = NULL; } } protected: CSingleton() { cout<<"CSingleton"<<endl; }; static CSingleton * m_pInstance; }; CSingleton* CSingleton::m_pInstance = NULL; int main(){ CSingleton* pSingleton1 = CSingleton::GetInstance(); CSingleton* pSingleton2 = CSingleton::GetInstance(); if(pSingleton1 == pSingleton2) { cout << "Produced one instance !"<<endl; pSingleton1->Release(); } else { cout << " Produced two instances !"<<endl; pSingleton1->Release(); pSingleton2->Release(); } return 0; }为了防止从类的外部调用构造函数,产生类的新的实例,我们应该把该类的构造函数声明成protected或者private。
如果构造过,那么就把之前构造的那个实例返回。为了保证之前构造的实例,在程序运行期间一直存在,不被析构,我们只能把指向这个实例的指针声明成静态变量,
存放在静态存储区,把这个类的实例用new来构造,并放在堆里。
//2) #include<iostream> using namespace std; class finalclass { public: static int count; public: static finalclass *getinstance() { if(count <= 0) return NULL; count--; return new finalclass; } static void setcount(int n) { count = n; } private: finalclass(){} ~finalclass(){} }; int finalclass::count = 0; int main() { finalclass::setcount(3); finalclass *f1 = finalclass::getinstance(); finalclass *f2 = finalclass::getinstance(); finalclass *f3 = finalclass::getinstance(); if(f3 == NULL) printf("f3 NULL\n"); else printf("f3 NOT NULL\n"); finalclass *f4 = finalclass::getinstance(); if(f4 == NULL) printf("f4 NULL\n"); finalclass *f5 = finalclass::getinstance(); if(f5 == NULL) printf("f5 NULL\n"); }
参考:http://www.cppblog.com/dyj057/archive/2005/09/20/346.html
http://www.2cto.com/kf/201304/202169.html
mark:
http://www.cnblogs.com/08shiyan/archive/2012/03/16/2399617.html
设计一个类,只能实现1个实例或3个实例,布布扣,bubuko.com
原文:http://blog.csdn.net/walkerkalr/article/details/20157009