单例模式定义:
Ensure a class has only one instance, and provide a global point of access to it.(确保类只有一个实例,自行实例化并向整个系统提供这个实例)
UML类图:

C++实现代码:
#include <iostream>
using namespace std;
class MMORPG {
public:
void Setup() { cout << "打开客户端" << endl; }
};
class Singleton : public MMORPG {
public:
static Singleton* GetInstance() {
if (_instance==NULL) { //非线程安全
_instance = new Singleton();
}
return _instance;
}
~Singleton() {
if (_instance!=NULL)
delete _instance;
}
private:
Singleton() { }
Singleton(const Singleton&) { }
Singleton& operator= (const Singleton&) { }
protected:
static Singleton* _instance;
};
Singleton* Singleton::_instance = NULL;#include "Singleton.h"
int main()
{
for (int times=0; times<10; ++times)
{
Singleton* pSingleton = Singleton::GetInstance();
pSingleton->Setup();
}
return 0;
}应用扩展:
1,有上限的多例模式
2,配合(抽象)工厂模式一起使用
单例模式详解
本文详细介绍了单例模式的概念及其在C++中的实现方式,并通过一个MMORPG客户端的例子进行了演示。此外,还讨论了单例模式的应用场景及扩展用法。
1509

被折叠的 条评论
为什么被折叠?



