模板类单例模式

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 ~

 

转载于:https://www.cnblogs.com/chuanyang/p/6489098.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值