第一种
#include <iostream>
#include <stdio.h>
using namespace std;
class Singleton {
private:
Singleton() {
printf("Singleton() construct\n");
}
static Singleton* m_pObject;
public:
static Singleton* CreateObject(){
if(m_pObject == nullptr){
m_pObject = new Singleton();
}
return m_pObject;
}
~Singleton() {
printf("~Singleton() destruct\n");
}
};
Singleton* Singleton::m_pObject = nullptr;
int main() {
Singleton* pObj1 = Singleton::CreateObject();
Singleton* pObj2 = Singleton::CreateObject();
cout << pObj1 << endl;
cout << pObj2 << endl;
return 0;
}
第二种
#include <iostream>
#include <stdio.h>
using namespace std;
class Singleton {
private:
Singleton() {
printf("Singleton() construct\n");
}
static Singleton* m_pObject;
public:
static Singleton* CreateObject() {
static Singleton obj;
return &obj;
}
~Singleton() {
printf("~Singleton() destruct\n");
}
};
int main() {
Singleton* pObj1 = Singleton::CreateObject();
Singleton* pObj2 = Singleton::CreateObject();
cout << pObj1 << endl;
cout << pObj2 << endl;
return 0;
}
第三种
#include <iostream>
#include <stdio.h>
using namespace std;
class Singleton {
private:
Singleton() {
printf("Singleton() construct\n");
}
public:
static Singleton& CreateObject() {
static Singleton obj;
return obj;
}
~Singleton() {
printf("~Singleton() destruct\n");
}
};
int main() {
Singleton& pObj1 = Singleton::CreateObject();
Singleton& pObj2 = Singleton::CreateObject();
cout << &pObj1 << endl;
cout << &pObj2 << endl;
return 0;
}
第四种
#include <iostream>
#include <stdio.h>
using namespace std;
class Singleton {
private:
Singleton() {
printf("Singleton() construct\n");
}
Singleton(const Singleton& obj) = delete;
public:
static Singleton& CreateObject() {
static Singleton obj;
return obj;
}
~Singleton() {
printf("~Singleton() destruct\n");
}
};
int main() {
Singleton& pObj1 = Singleton::CreateObject();
Singleton pObj2 = Singleton::CreateObject();
cout << &pObj1 << endl;
cout << &pObj2 << endl;
return 0;
}
总结
给自己看的,单例模式的巧妙,是真的巧,不仅仅是只能实现一个对象,更重要的是在编译前就已经知道了,对象的大小,这样才能在内部实现一个对象初始化。
|