概念
單例模式是確保一個變量只有一個實例,並提供一個全局的角度進行訪問.
類圖
示例代碼
[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