设计一个类,只能实现1个实例或3个实例

2014-11-24 02:08:37 · 作者: · 浏览: 0
/*********************************************
题目:	1)设计一个类,我们只能生成该类的一个实例
	2)设计一个类,只能生成该类的3个实例
******************************************/
//1)
#include
  
   
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"<
   
    Release(); } else { cout << " Produced two instances !"<
    
     Release(); pSingleton2->Release(); } return 0; } 
    
   
  
为了防止从类的外部调用构造函数,产生类的新的实例,我们应该把该类的构造函数声明成protected或者private。
由于只能生成一个类的实例,我们可以考虑用静态成员函数来记录,到底之前有没有构造过类的实例。如果没有构造过,那么就构造一个新的实例。

如果构造过,那么就把之前构造的那个实例返回。为了保证之前构造的实例,在程序运行期间一直存在,不被析构,我们只能把指向这个实例的指针声明成静态变量,

存放在静态存储区,把这个类的实例用new来构造,并放在堆里。

//2)
#include
  
   
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