GOF的《设计模式》中这样描述:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
class CS
{
public:
static CS *ins()
{
return m_pCS;
}
int func(){ return 0;}
private:
CS() // 构造函数私有
{
if ( 0==m_pCS) // 保证一个实例
{
m_pCS = new CS();
}
}
static CS *m_pCS;
};
CS* CS::m_pCS= 0;
void main()
{
CS* pCS = CS::ins();
int n = pCS->func();
}
{
public:
static CS *ins()
{
return m_pCS;
}
int func(){ return 0;}
private:
CS() // 构造函数私有
{
if ( 0==m_pCS) // 保证一个实例
{
m_pCS = new CS();
}
}
static CS *m_pCS;
};
CS* CS::m_pCS= 0;
void main()
{
CS* pCS = CS::ins();
int n = pCS->func();
}
GOF的《设计模式》中这样描述:保证一个类仅有一个实例,并提供一个访问它的全局访问点。通常我们可以让一个全局变量使得一个对象被访问,但它不能阻止你实例化多个对象。一个最好的办法是,让类自身负责保存它的唯一实例。这个类可以保证没有其他实例可以被创建,并且它可以提供一个访问该实例的方法。
也就是说,很多时候我们需要全局的对象,如一个工程中,数据库访问对象只有一个,这时,可以考虑使用单例模式。单例模式比全局对象好还包括:单例类可以继承,如下例。
单例模式的关键点在于:构造函数私有,静态的GetInstance。
另外,在C++中必须注意内存的释放。C++、Java、C#中还要注意多线程时的同步问题。
#include <iostream.h>
class CSingleton
{
public:
static CSingleton * GetInstance()
{
if(NULL == m_pInstance)
m_pInstance = new CSingleton();
return m_pInstance;
}
static void Release() // 必须,否则会导致内存泄露
{
if(NULL != m_pInstance)
{
delete m_pInstance;
m_pInstance = NULL;
}
}
protected:
CSingleton()
{
cout<< " CSingleton "<<endl;
};
static CSingleton * m_pInstance;
};
CSingleton* CSingleton::m_pInstance = NULL;
class CSingleDraw: public CSingleton
{
public:
static CSingleDraw* GetInstance()
{
if(NULL == m_pInstance)
m_pInstance = new CSingleDraw();
return (CSingleDraw*)m_pInstance;
}
protected:
CSingleDraw()
{
cout<< " CSingleDraw "<<endl;
}
};
int main()
{
CSingleDraw* s1 = CSingleDraw::GetInstance();
CSingleDraw* s2 = CSingleDraw::GetInstance();
s2->Release();
return 0;
}
class CSingleton
{
public:
static CSingleton * GetInstance()
{
if(NULL == m_pInstance)
m_pInstance = new CSingleton();
return m_pInstance;
}
static void Release() // 必须,否则会导致内存泄露
{
if(NULL != m_pInstance)
{
delete m_pInstance;
m_pInstance = NULL;
}
}
protected:
CSingleton()
{
cout<< " CSingleton "<<endl;
};
static CSingleton * m_pInstance;
};
CSingleton* CSingleton::m_pInstance = NULL;
class CSingleDraw: public CSingleton
{
public:
static CSingleDraw* GetInstance()
{
if(NULL == m_pInstance)
m_pInstance = new CSingleDraw();
return (CSingleDraw*)m_pInstance;
}
protected:
CSingleDraw()
{
cout<< " CSingleDraw "<<endl;
}
};
int main()
{
CSingleDraw* s1 = CSingleDraw::GetInstance();
CSingleDraw* s2 = CSingleDraw::GetInstance();
s2->Release();
return 0;
}