微软100题(72)单例模式

来源:互联网 发布:网络直播飙车 编辑:程序博客网 时间:2024/06/11 01:40
题目:设计一个类,我们只能生成该类的一个实例。

分析:只能生成一个实例的类是实现了Singleton模式的类型。


单例模式

[cpp] view plaincopy
  1. class Singleton  
  2. {  
  3. private:  
  4.     Singleton(){};  
  5.     static Singleton* instance = NULL;  
  6. public:  
  7.     static Singleton* GetInstance()  
  8.     {  
  9.         if(instance == NULL)  
  10.             instance = new Singleton();  
  11.         return instance;  
  12.     }  
  13. };  

考虑自动销毁的话,则:

[cpp] view plaincopy
  1. class Singleton  
  2. {  
  3. private:  
  4.     Singleton(){};  
  5.     static Singleton* instance = NULL;  
  6.     class CGarbo//唯一工作时删除instance实例  
  7.     {  
  8.     public:  
  9.         ~CGarbo()  
  10.         {  
  11.             if(Singleton::instance) delete Singleton::instance;  
  12.         }  
  13.     };  
  14.     static CGarbo Garbo;//定义一个静态变量,程序结束时,自动调用其析构函数  
  15. public:  
  16.     static Singleton* GetInstance()  
  17.     {  
  18.         if(instance == NULL)  
  19.             instance = new Singleton();  
  20.         return instance;  
  21.     }  
  22. };  

0 0
原创粉丝点击