题目:设计一个类,我们只能生成该类的一个实例。
分析:只能生成一个实例的类是实现了Singleton模式的类型。
单例模式
- class Singleton
- {
- private:
- Singleton(){};
- static Singleton* instance = NULL;
- public:
- static Singleton* GetInstance()
- {
- if(instance == NULL)
- instance = new Singleton();
- return instance;
- }
- };
考虑自动销毁的话,则:
- class Singleton
- {
- private:
- Singleton(){};
- static Singleton* instance = NULL;
- class CGarbo
- {
- public:
- ~CGarbo()
- {
- if(Singleton::instance) delete Singleton::instance;
- }
- };
- static CGarbo Garbo;
- public:
- static Singleton* GetInstance()
- {
- if(instance == NULL)
- instance = new Singleton();
- return instance;
- }
- };