c++单例模式
1 /** 2 * 3 * 文件名称:singleton.cpp 4 * 文件标识:见配置管理说明书 5 * 摘 要:单例模式演示 6 * 7 * 版 本:1.0 8 * 作 者:luwei 9 * 完成日期:12-12-6 10 * 11 **/ 12 #include <iostream> 13 14 using std::cout; 15 using std::cin; 16 using std::endl; 17 18 // 单例模式 Singleton 类 19 class Singleton{ 20 public: 21 // 获得一个实例,必须为静态成员函数,因为会在存在对象之前调用 22 static Singleton * getInstance(void) 23 { 24 if(NULL == m_ptr) 25 { 26 m_ptr = new Singleton; 27 } 28 29 return m_ptr; 30 } 31 32 private: 33 34 // 构造函数私有,防止实例化任意对象 35 Singleton() {} 36 37 // 记录对象的地址,必须为静态成员,因为会在存在对象之前使用 38 static Singleton *m_ptr; 39 }; 40 41 // 初始化静态数据成员 42 Singleton *Singleton::m_ptr = NULL; 43 44 int main(void) 45 { 46 //Singleton a; // 错误 47 48 Singleton *a = Singleton::getInstance(); // 正确 49 Singleton *b = Singleton::getInstance(); 50 51 // 其实 a 和 b 指向同一个对象,因为本身自始至终就只能实例化一个对象 52 cout<< a << endl << b <<endl; 53 54 system("PAUSE"); 55 return 0; 56 }
附: http://pan.baidu.com/share/link?shareid=147883&uk=1596008112
c++23种设计模式.pdf