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);
}
/************************************************************************/