单例模式定义:
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,配合(抽象)工厂模式一起使用