单例的实现方法
一种方法:
Singleton.h代码如下:
View Code
1 #ifndef _SINGLETON_H_ 2 #define _SINGLETON_H_ 3 4 class Singleton 5 { 6 public: 7 int getValue(); 8 static Singleton* Instance(); 9 private: 10 Singleton(); 11 ~Singleton(); 12 13 int _iValue; 14 static Singleton* _Instance; 15 }; 16 #endif
Singleton.cpp代码如下:
View Code
1 #include "Singleton.h" 2 #include <cstdlib> 3 4 Singleton* Singleton::_Instance = NULL; 5 6 Singleton::Singleton() 7 { 8 9 } 10 Singleton::~Singleton() 11 { 12 if (NULL != _Instance) 13 { 14 delete _Instance; 15 _Instance = NULL; 16 } 17 } 18 Singleton* Singleton::Instance() 19 { 20 if (NULL == _Instance) 21 { 22 _Instance = new Singleton; 23 } 24 return _Instance; 25 } 26 int Singleton::getValue() 27 { 28 return _iValue; 29 }
测试代码如下:
View Code
1 #include "Singleton.h" 2 #include <cstdlib> 3 4 int main(int argc, char** argv) 5 { 6 int value = Singleton::Instance()->getValue(); 7 return EXIT_SUCCESS; 8 }
另外的方法:
Singleton.h代码如下:
View Code
1 #ifndef _SINGLETON_H_ 2 #define _SINGLETON_H_ 3 4 class Singleton 5 { 6 public: 7 int getValue(); 8 static Singleton* Instance(); 9 private: 10 Singleton(); 11 ~Singleton(); 12 13 int _iValue; 14 }; 15 #endif
Singleton.cpp代码如下:
View Code
1 #include "Singleton.h" 2 #include <cstdlib> 3 4 Singleton* Singleton::_Instance = NULL; 5 6 Singleton::Singleton() 7 { 8 9 } 10 Singleton::~Singleton() 11 { 12 13 } 14 Singleton* Singleton::Instance() 15 { 16 static Singleton m_Singleton; 17 return &m_Singleton; 18 } 19 int Singleton::getValue() 20 { 21 return _iValue; 22 }