C++中的单例模式

C++编程语言中,单例模式应用的例子如下述代码所示(这里仅仅提供一个示例;由于加入了锁,这代码是线程安全的):

  1 // ...
  2 
  3 class lock
  4 {
  5     public:
  6         lock();
  7         lock(lock const & l);
  8         ~lock();
  9         lock & operator =(lock const & l);
 10         void request();
 11         void release();
 12     // ...
 13 };
 14 
 15 lock::lock()
 16 {
 17     // ...
 18 }
 19 
 20 // ...
 21 
 22 lock::~lock()
 23 {
 24     // ...
 25 }
 26 
 27 // ...
 28 
 29 void lock::request()
 30 {
 31     // ...
 32 }
 33 
 34 void lock::release()
 35 {
 36     // ...
 37 }
 38 
 39 // ...
 40 
 41 // assumes _DATA_TYPE_ has a default constructor
 42 template<typename _DATA_TYPE_>
 43 class singleton
 44 {
 45     public:
 46         static _DATA_TYPE_ * request();
 47         static void release();
 48 
 49     private:
 50         singleton();
 51         singleton(singleton<_DATA_TYPE_> const & s);
 52         ~singleton();
 53         singleton<_DATA_TYPE_> & operator =(singleton<_DATA_TYPE_> const & s);
 54         static _DATA_TYPE_ * pointer;
 55         static lock mutex;
 56     // ...
 57 };
 58 
 59 template<typename _DATA_TYPE_>
 60 _DATA_TYPE_ * singleton<_DATA_TYPE_>::pointer = nullptr;
 61 
 62 template<typename _DATA_TYPE_>
 63 lock singleton<_DATA_TYPE_>::mutex;
 64 
 65 template<typename _DATA_TYPE_>
 66 _DATA_TYPE_ * singleton<_DATA_TYPE_>::request()
 67 {
 68     if(singleton<_DATA_TYPE_>::pointer == nullptr)
 69     {
 70         singleton<_DATA_TYPE_>::mutex.request();
 71 
 72         if(singleton<_DATA_TYPE_>::pointer == nullptr)
 73         {
 74             singleton<_DATA_TYPE_>::pointer = new _DATA_TYPE_;
 75         }
 76 
 77         singleton<_DATA_TYPE_>::mutex.release();
 78     }
 79 
 80     return singleton<_DATA_TYPE_>::pointer;
 81 }
 82 
 83 template<typename _DATA_TYPE_>
 84 void singleton<_DATA_TYPE_>::release()
 85 {
 86     if(singleton<_DATA_TYPE_>::pointer != nullptr)
 87     {
 88         singleton<_DATA_TYPE_>::mutex.request();
 89 
 90         if(singleton<_DATA_TYPE_>::pointer != nullptr)
 91         {
 92             delete singleton<_DATA_TYPE_>::pointer;
 93  
 94             singleton<_DATA_TYPE_>::pointer = nullptr;
 95         }
 96 
 97         singleton<_DATA_TYPE_>::mutex.release();
 98     }
 99 }
100 
101 template<typename _DATA_TYPE_>
102 singleton<_DATA_TYPE_>::singleton()
103 {
104     // ...
105 }
106 
107 // ...
108 
109 int main()
110 {
111     int * s;
112 
113     s = singleton<int>::request();
114 
115     // ...
116 
117     singleton<int>::release();
118 
119     return 0;
120 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值