以前看过高手写的单例实现,也是利用继承模板基类来实现,最近正要用到单例模式,却苦于找不到以前高手的代码,于是就自己动手实现,代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
template<typename T> class Singletion { friend T; private: Singletion(){} virtual ~Singletion(){} static T* pObject; //利用此类析构函数释放单例实例内存 class CCarbageCollector { public: ~CCarbageCollector() { printf("~CCarbageCollector"); if(Singletion<T>::pObject != NULL) { delete Singletion<T>::pObject; printf("Object delete"); } } }; protected: //提供给单例类的初始化接口 virtual void Init()=0; public: //获取单例 inline static T* GetSingleton() { //用于系统退出时释放单例实例的内存 static Singletion<T>::CCarbageCollector CarCo; pObject==NULL && (pObject=new T); return pObject; } }; template<typename T> T* Singletion<T>::pObject = NULL; #define SINGLETON_INIT(ClassType)\ friend ClassType* Singletion<ClassType>::GetSingleton();\ friend Singletion<ClassType>::CCarbageCollector;\ private:\ ClassType(){Init();}\ virtual ~ClassType(){}\ virtual void Init() //单例 class B:public Singletion<B> { SINGLETON_INIT(B) { printf("Singleton Init"); } }; int _tmain(int argc, _TCHAR* argv[]) { B *b = B::GetSingleton(); //B bb; //->error //new B; //->error ::system("pause"); } |
发表评论
要发表评论,您必须先登录。