在Linux下使用单件Singleton模式


1. Singleton.h文件

  1. /* 
  2.  * Singleton.h 
  3.  */  
  4.   
  5. #ifndef SINGLETON_H_   
  6. #define SINGLETON_H_   
  7.   
  8. #include <assert.h>   
  9. template <typename T> class Singleton  
  10. {  
  11. protected:  
  12.     static T* mSingleton;  
  13. public:  
  14.     Singleton()  
  15.     {  
  16.         assert(!mSingleton);  
  17.         mSingleton=static_cast< T*>(this);  
  18.     }  
  19.     ~Singleton()  
  20.     {  
  21.         assert(mSingleton);  
  22.         delete mSingleton;  
  23.         mSingleton=0;  
  24.     }  
  25.     static T* getSingletonPtr()  
  26.     {  
  27.         assert(!mSingleton);  
  28.         return mSingleton;  
  29.     }  
  30.     static T& getSingleton()  
  31.     {  
  32.         assert(!mSingleton);  
  33.         return *mSingleton;  
  34.     }  
  35. };  
  36. #endif /* SINGLETON_H_ */  

2. 类SubClass继承并实例化模板类Singleton

  1. /* 
  2.  * SubClass.h 
  3.  */  
  4. #ifndef SUBCLASS_H_   
  5. #define SUBCLASS_H_   
  6. #include "Singleton.h"   
  7. #include <iostream>   
  8. using namespace std;  
  9. class SubClass:public Singleton<SubClass>  
  10. {  
  11. public:  
  12.     SubClass();  
  13.     virtual ~SubClass();  
  14.     inline void Show()  
  15.     {  
  16.         static int s=0;  
  17.         s++;  
  18.         cout<<"s===="<<s<<endl;  
  19.     }  
  20. };  
  21. #endif /* SUBCLASS_H_ */   
  22.   
  23.   
  24.   
  25. /* 
  26.  * SubClass.cpp 
  27.  */  
  28. #include "SubClass.h"   
  29. template<> SubClass* Singleton<SubClass>::mSingleton=0;  
  30. SubClass::SubClass()  
  31. {  
  32. }  
  33. SubClass::~SubClass()  
  34. {  
  35. }  

3. 使用函数SubClass::Show()

#include "SubClass.h"

SubClass::getSingletonPtr()->Show();

相关内容