C++单例模式简介

1、懒汉式

class CSingleton
{
public:
static CSingleton* GetInstance()
{
     if ( m_pInstance == NULL )  
         m_pInstance = new CSingleton();
     return m_pInstance;
}
private:
    CSingleton(){};
    static CSingleton * m_pInstance;
};


2、饿汉式

class CSingleton  
{  
private:  
    CSingleton()  
    {  
    }  
    static CSingleton *m_pInstance;  
    class CGarbo   
    {  
    public:  
        ~CGarbo()  
        {  
            if(CSingleton::m_pInstance)  
                delete CSingleton::m_pInstance;  
        }  
    };  
    static CGarbo Garbo;   
public:  
    static CSingleton * GetInstance()  
    {  
        if(m_pInstance == NULL)  
            m_pInstance = new CSingleton();  
        return m_pInstance;  
    }  
};  
 

3、多线程下的单例模式

class Singleton
{
private:
    static Singleton* m_instance;
    Singleton(){}
public:
    static Singleton* getInstance();
};
 
Singleton* Singleton::getInstance()
{
    if(NULL == m_instance)
    {
        Lock();//借用其它类来实现,如boost
        if(NULL == m_instance)
        {
            m_instance = new Singleton;
        }
        UnLock();
    }
    return m_instance;
}
 

4、单例模板

Singleton.h

/************************************************************************/
/* 单例模式: Singleton.h                                                              */
/************************************************************************/

#pragma once

template <typename T>
class CSingleton
{
private:
 CSingleton( )
 {
  if(NULL == m_instance)
  {
   m_instance = new T();
  }
 }
 ~CSingleton()
 { 
  if(m_instance)
   delete m_instance;
  m_instance = NULL;
 }
 class CGarbo  
 { 
 public: 
  ~CGarbo() 
  { 
   if(CSingleton::m_instance) 
    delete CSingleton::m_instance; 
  } 
 }; 
 static CGarbo Garbo;  
public:
 inline static T* Instance()
 {
  static CSingleton i;
  return m_instance;
 }
 static T* m_instance;
};
template<typename T>
T* CSingleton<T>::m_instance = NULL;

#define INSTANCE(CLASS) CSingleton<CLASS>::Instance()
#define SINGLETON(CLASS) friend CSingleton<CLASS>

/************************************************************************/

5、单例调用

/************************************************************************/
/* 单例模式: Cadd.cpp                                                                 */
/************************************************************************/

class Cadd{
public:
 Cadd(){
  printf("Cadd()\n");
 }

 ~Cadd(){
  printf("~Cadd()\n");
 }
};

void main(){

  Cadd pCadd = INSTANCE(Cadd);

/************************************************************************/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值