单例模式
最后更新于:2022-04-01 20:29:25
## 模式定义:
单例模式确保一个类只有一个实例,并提供一个全局访问点。
## 模式结构:
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-30_57c5458f38c59.jpg)
## 单例模式编程实现及执行结果:
~~~
#include
using namespace std;
~~~
单例类
~~~
class Sigleton
{
public:
static Sigleton* getInstance(); //必须是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;
};
';
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** **请按任意键继续. . .**