## 模式定義:
? ? ? 單例模式確保一個類只有一個實例,并提供一個全局訪問點。
## 模式結構:

## 單例模式編程實現及執行結果:
~~~
#include <iostream>
using namespace std;
~~~
? ? ? 單例類
~~~
class Sigleton
{
public:
static Sigleton* getInstance();<span style="white-space:pre"> </span>//必須是static,否則無法調用getInstance
private:
Sigleton(){}
static Sigleton* uniqueInstance;
};
~~~
? ? ? 靜態成員初始化
~~~
Sigleton* Sigleton::uniqueInstance = NULL;
~~~
? ? ? 成員函數實現?
~~~
Sigleton* Sigleton::getInstance()
{
if(uniqueInstance == NULL)
{
uniqueInstance = new Sigleton();
}
return uniqueInstance;
}
~~~
? ? ? 客戶代碼
~~~
int main()
{
Sigleton* pSigleton1 = Sigleton::getInstance();
Sigleton* pSigleton2 = Sigleton::getInstance();
if(pSigleton1 == pSigleton2)
cout << "Sigleton Successful" << endl;
else
cout << "Sigleton failue" << endl;
return 0;
}
~~~
執行結果:
**Sigleton?Successful**
**請按任意鍵繼續. . .**
## 應用:創建Sigleton類的子類
? ? ? 我們應當考慮Sigleton的多個子類,而且應用必須決定使用哪一個子類。修改Sigleton方法如下:
? ? ? 單例基類
~~~
class Sigleton
{
public:
static Sigleton* getInstance(const char* name);
virtual void show(){cout << "Sigleton" << endl;}
protected: //基類構造函數訪問權限位protected,使子類構造函數可以調用基類構造函數
Sigleton(){}
private:
static Sigleton* uniqueInstance;
};?<pre name="code" class="cpp">Sigleton* Sigleton::uniqueInstance = NULL;
Sigleton* Sigleton::getInstance(const char* name)
{
if(uniqueInstance == NULL)
{
if(strcmp(name,"SigletonA") == 0)
{
uniqueInstance = new SigletonA();
}
else if(strcmp(name,"SigletonB") == 0)
{
uniqueInstance = new SigletonB();
}
else
{
uniqueInstance = new Sigleton();
}
}
return uniqueInstance;
}
~~~
? ? A類子類
~~~
class SigletonA : public Sigleton
{
//聲明基類為友元,使其可以訪問A類私有構造函數
friend class Sigleton;
public:
void show(){cout << "SigletonA" << endl;}
private:
SigletonA(){}
};
~~~
? ? ??B子類
~~~
class SigletonB : public Sigleton
{
friend class Sigleton;
public:
void show(){cout << "SigletonB" << endl;}
private:
SigletonB(){}
};
~~~
? ? ? 客戶代碼
~~~
int main()
{
Sigleton* pSigleton1 = Sigleton::getInstance("SigletonA");
Sigleton* pSigleton2 = Sigleton::getInstance("SigletonA");
Sigleton* pSigleton3 = Sigleton::getInstance("SigletonB");
Sigleton* pSigleton4 = Sigleton::getInstance("SigletonB");
if(pSigleton1 == pSigleton2)
cout << "SigletonA Successful" << endl;
else
cout << "SigletonA failue" << endl;
pSigleton1->show();
pSigleton3->show();
return 0;
}
~~~
執行結果:
**SigletonA? Successful**
**SigletonA**
**SigletonA**
**請按任意鍵繼續. . .**