单例模式
其他二十三种设计模式
#include<iostream>
using namespace std;
class Singleton_lazy {
private:
Singleton_lazy() {
cout << "懒汉" << endl; }
static Singleton_lazy* pSingleton;
public:
static Singleton_lazy* GetInstance() {
if (pSingleton ==NULL)
{
pSingleton = new Singleton_lazy();
}
return pSingleton;
}
};
Singleton_lazy* Singleton_lazy::pSingleton = NULL;
class Singleton_hungry {
private:
Singleton_hungry() {
cout << "饿汉" << endl; }
static Singleton_hungry* pSingleton;
public:
static Singleton_hungry* GetInstance() {
return pSingleton;
}
};
Singleton_hungry* Singleton_hungry::pSingleton = new Singleton_hungry;
void test1() {
Singleton_lazy* s1 = Singleton_lazy::GetInstance();
Singleton_lazy* s2 = Singleton_lazy::GetInstance();
if (s1 == s2)
{
cout << "为同一实例" << endl;
}
}
int main()
{
test1();
return 0;
}