单件类模板的继承实现

参考了网上一些资料,写了个单件类模板的继承实现。把单件定义为类模板,让所有需要实现单件的类都去继承这个单件类模板,从而保证每一个类只有一个实例。

 

1 #include "stdafx.h"
2 #include <iostream>
3  using namespace std;
4 /* 单件模板 */
5 template<class T>
6 class Singleton
7 {
8 public:
9 static T* getInstance()
10 {
11 if (NULL == m_Instance )
12 {
13 m_Instance = new T;
14 }
15 return m_Instance;
16 }
17 static void releaseInstance()
18 {
19 if(NULL != m_Instance)
20 delete m_Instance;
21 m_Instance=NULL;
22 cout<<"memory released..."<<endl;
23 }
24 protected:
25 Singleton()
26 {
27 cout<<"singleton constructor..."<<endl;
28 }
29 virtual ~Singleton()
30 {
31 cout<<"singleton destructor..."<<endl;
32 }
33
34 private:
35 Singleton(const Singleton& );
36 Singleton& operator= (const Singleton& );
37
38 private:
39 static T* m_Instance;
40 };
41 template<class T>
42 T* Singleton<T>::m_Instance=NULL;
43
44
45 class App : public Singleton<App>
46 {
47 public:
48 friend class Singleton<App>;
49 void print() const
50 {
51 cout<<"hi,marrywindy"<<endl;
52 }
53 private:
54 App()
55 {
56 cout<<"app constructor..."<<endl;
57 }
58 ~App()
59 {
60 cout<<"app destructor..."<<endl;
61 }
62 private:
63 App(const App&);
64 App& operator= (const App& );
65 };
66
67
68 int _tmain(int argc, _TCHAR* argv[])
69 {
70 App::getInstance()->print();
71 App::releaseInstance();
72 return 0;
73 }
74
75

欢迎大侠们指正....

posted on 2010-12-23 10:58  marrywindy  阅读(1361)  评论(0编辑  收藏  举报

导航