模板Singleton

// 使用SingletonT可以确保使用SingletonT获得的相同类的对像是唯一的。
#pragma once

#ifndef _SINGLETONT_H_
#define _SINGLETONT_H_

template
   
   
    
    
class SingletonT
{
protected:
    SingletonT(void);
public:
    virtual ~SingletonT(void);
public:
    static T* Instance();
private:
    static T* _instance;
};


#ifdef _DEBUG
#include 
    
    
     
     
using namespace std;
#endif // _DEBUG

template
     
     
      
      
T* SingletonT
      
      
       
       ::_instance = 0;

template
       
       
         SingletonT 
        
          ::SingletonT(void) { #ifdef _DEBUG cout<<"SingletonT"< 
         
           SingletonT 
          
            ::~SingletonT(void) { #ifdef _DEBUG cout<<"~SingletonT"< 
           
             T* SingletonT 
            
              ::Instance() { if (_instance == 0) { #ifdef _DEBUG cout<<"Instance T"< 
             
               class SingletonT { public: SingletonT(){} ~SingletonT(){} static T* GetInstance() { static T t; return &t; } private: enum{ value = v}; }; #ifndef __SINGLETONSAFET_H__ #define __SINGLETONSAFET_H__ #include 
              
                #include 
               
                 / // 工程: // 作者: // 描述: // 主要函数: // 日期: // 版本: 1.0 // 修改: / class CLocker { public: CLocker() { InitializeCriticalSection(&m_cs); } ~CLocker() { DeleteCriticalSection(&m_cs); } void Lock() { EnterCriticalSection(&m_cs); } void UnLock() { LeaveCriticalSection(&m_cs); } private: CRITICAL_SECTION m_cs; }; / // 工程: // 作者: // 描述: 单例模版类 // 主要函数: // 日期: // 版本: 1.0 // 修改: / template 
                
                  class SingletonSafeT { public: static T* GetInstance() { if (__instance == NULL) { Lock.Lock(); if (__instance == NULL) { __instance = new T(); } Lock.UnLock(); } return __instance; } SingletonSafeT(){}; ~SingletonSafeT(){ Release(); }; private: static T* __instance; static CLocker Lock; static void Release() { if (__instance != NULL) { Lock.Lock(); if (__instance != NULL) { delete __instance; __instance = NULL; } Lock.UnLock(); } } }; template 
                 
                   T* SingletonSafeT 
                  
                    ::__instance = NULL; template 
                   
                     CLocker SingletonSafeT 
                    
                      ::Lock; #endif // __SINGLETONSAFET_H__ 
                     
                    
                   
                  
                 
                
               
              
             
            
           
          
         
       
      
      
     
     
    
    
   
   


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值