1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| * Singleton.cpp * 单例模式 * Created on: 2016年3月11日 下午3:38:31 * Author: Wayne 13186259527@163.com */
#include <iostream>
using namespace std;
* 懒汉:需要创建时才创建对象 */ class Singleton { private: static Singleton * instance; Singleton() { } public: static Singleton * GetInstance() { if (instance == NULL) { instance = new Singleton(); } return instance; }
};
Singleton* Singleton::instance = NULL;
int main(void) { Singleton * s1 = Singleton::GetInstance(); Singleton * s2 = Singleton::GetInstance(); if (s1 == s2) { cout << "s1 == s2" << endl; } return 0; }
|