23种设计模式--单例模式(懒汉)
1 #include "stdafx.h" 2 3 //单例模式之懒汉模式 4 class Singleton 5 { 6 public: 7 static Singleton& GetInstance() 8 { 9 if(m_spInstance==NULL) 10 { 11 m_spInstance = new Singleton; 12 } 13 m_snCount++; 14 return *m_spInstance; 15 } 16 void ReleaseInstance() 17 { 18 m_snCount--; 19 if(m_snCount==0) 20 { 21 delete m_spInstance; 22 } 23 } 24 ~Singleton() 25 { 26 m_spInstance=NULL; 27 } 28 private: 29 //构造,拷贝构造 30 Singleton() {} 31 Singleton(Singleton& singleton) {} 32 //单例指针 33 static Singleton *m_spInstance; 34 //引用计数 35 static unsigned int m_snCount; 36 }; 37 Singleton* Singleton::m_spInstance=NULL; 38 unsigned int Singleton::m_snCount=0; 39 40 //测试用例 41 int main(int argc, char* argv[]) 42 { 43 Singleton& s1 = Singleton::GetInstance(); 44 Singleton& s2 = Singleton::GetInstance(); 45 printf("%p\n%p\n",&s1,&s2); 46 s1.ReleaseInstance(); 47 s2.ReleaseInstance(); 48 return 0; 49 }
注:该代码在VC6.0下测试通过
浙公网安备 33010602011771号