c++ 设计模式之 单例模式
概念
单例模式是确保一个变量只有一个实例,并提供一个全局的角度进行访问.
类图
示例代码
[cpp]
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *getInstance();
private:
Singleton(){}
static Singleton* instance;
};
Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance()
{
if(!instance) {
instance = new Singleton();
cout << "getInstance(): First instance\n";
return instance;
}
else {
cout << "getInstance(): previous instance\n";
return instance;
}
}
int main()
{
Singleton *s1 = Singleton::getInstance();
Singleton *s2 = Singleton::getInstance();
return 0;
}
作者:wpf_ml
补充:软件开发 , C++ ,