模板类单例模式

single.h

 1 #ifndef _SIGNAL_H_
 2 #define _SIGNAL_H_
 3 template<class TYPE >
 4 
 5 class Single
 6 {
 7 public:
 8         static TYPE* getInstance(void);
 9         static void destroy(void);
10 protected:
11         Single(void)
12         {
13         }
14         ~Single(void)
15         {
16                 //delete instance;
17         }
18         static TYPE* instance_;
19 };
20 
21 template<class TYPE>
22 TYPE* Single<TYPE>::instance_=0;
23 
24 template<class TYPE>
25 TYPE* Single<TYPE>::getInstance()
26 {
27         if(instance_ == 0)
28         {
29                 instance_ = new TYPE();
30         }
31         return instance_;
32 }
33 template<class TYPE>
34 void Single<TYPE>::destroy()
35 {
36         delete instance_;
37         instance_ = 0;
38 }
39 
40 #endif

模板类单例模式与单例类似,只要理解单例模式,上面的代码就很好理解

main.cpp

 1 #include "single.h"
 2 #include <string>
 3 #include <iostream>
 4 using namespace std;
 5 
 6 class student
 7 {
 8 public:
 9         student()
10         {
11                 num = 100;
12                 name = "hello world";
13         }
14         student(int n, string na)
15         {
16                 num = n;
17                 name = na;
18         }
19         string getName()
20         {
21                 return name;
22         }
23         int getNum()
24         {
25                 return num;
26         }
27 private:
28         int num;
29         string name;
30 };
31 typedef Single<student> st;
32 int main()
33 {
34         cout<<st::getInstance()->getNum()<<endl;
35         cout<<st::getInstance()->getName()<<endl;
36         cout<<Single<student>::getInstance()->getName()<<endl;
37         return 0;
38 }
39 ~

 

posted on 2017-03-02 10:03  川洋  阅读(346)  评论(0编辑  收藏  举报