单例模式:
问题:
如何定义一个类,使得这个类只能创建一个对象?
示例:
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 class SObject 7 { 8 static SObject* c_instance; 9 10 SObject(const SObject&); 11 SObject& operator= (const SObject&); 12 13 SObject() 14 { 15 } 16 public: 17 static SObject* GetInstance(); 18 19 void print() 20 { 21 cout << "this = " << this << endl; 22 } 23 }; 24 25 SObject* SObject::c_instance = NULL; 26 27 SObject* SObject::GetInstance() 28 { 29 if( c_instance == NULL ) 30 { 31 c_instance = new SObject(); 32 } 33 34 return c_instance; 35 } 36 37 int main() 38 { 39 SObject* s = SObject::GetInstance(); 40 SObject* s1 = SObject::GetInstance(); 41 SObject* s2 = SObject::GetInstance(); 42 43 s->print(); 44 s1->print(); 45 s2->print(); 46 47 return 0; 48 }
运行结果如下:
可以看到这里打印的地址是一样的。
单例类对象在整个系统的运行过程中一般是不释放的。
存在的问题:
解决方案:
程序如下:
1 #ifndef _SINGLETON_H_ 2 #define _SINGLETON_H_ 3 4 template 5 < typename T > 6 class Singleton 7 { 8 static T* c_instance; 9 public: 10 static T* GetInstance(); 11 }; 12 13 template 14 < typename T > 15 T* Singleton<T>::c_instance = NULL; 16 17 template 18 < typename T > 19 T* Singleton<T>::GetInstance() 20 { 21 if( c_instance == NULL ) 22 { 23 c_instance = new T(); 24 } 25 26 return c_instance; 27 } 28 29 30 #endif
主函数:
1 #include <iostream> 2 #include <string> 3 #include "Singleton.h" 4 5 using namespace std; 6 7 class SObject 8 { 9 friend class Singleton<SObject>; // 当前类需要使用单例模式 10 11 SObject(const SObject&); 12 SObject& operator= (const SObject&); 13 14 SObject() 15 { 16 } 17 public: 18 19 void print() 20 { 21 cout << "this = " << this << endl; 22 } 23 }; 24 25 int main() 26 { 27 SObject* s = Singleton<SObject>::GetInstance(); 28 SObject* s1 = Singleton<SObject>::GetInstance(); 29 SObject* s2 = Singleton<SObject>::GetInstance(); 30 31 s->print(); 32 s1->print(); 33 s2->print(); 34 35 return 0; 36 }
第9行将使用当前类作为参数的类模板声明为友元,使得能够调用当前类的构造函数。
运行结果如下:
小结: