Student.h
1:
2: #ifndef __SINGLETON_H__
3: #define __SINGLETON_H__
4:
5: #include <memory>
6:
7: template<class T>
8: class SingleT
9: {
10: public:
11: static T * Instance()
12: {
13: if (!p)
14: {
15: p = new T;
16: }
17:
18: return p;
19: }
20:
21: static void Create()
22: {
23: if (!p)
24: {
25: p = new T;
26: }
27: }
28:
29: static void Destroy()
30: {
31: if (p)
32: {
33: delete p;
34: p = NULL;
35: }
36: }
37:
38: static T * Get()
39: {
40: return p;
41: }
42:
43: static void Reset()
44: {
45: Destroy();
46: Create();
47: }
48:
49: protected:
50: static T * p;
51: };
52:
53: template <class T>
54: T * SingleT<T>::p = NULL;
55:
56: #endif
57:
定义另外一个测试类:SingletonTest.h
1:
2: #ifndef __SINGLETONTEST_H__
3: #define __SINGLETONTEST_H__
4:
5: #include "Singleton.h"
6:
7: #include <iostream>
8:
9: class SingletonTest : public SingleT<SingletonTest>
10: {
11: public:
12: SingletonTest(){};
13: ~SingletonTest(){};
14:
15: public:
16: inline void test() {std::cout<<"test()"<<std::endl;}
17: };
18:
19: #endif
调用测试:SingletonTest::Instance()->test();