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;
}