C++中单例模式(Singleton)的简单实现

单例模式(Singleton)是设计模式中最为简单的模式之一,用于实现类的实例化.

以下代码将实现单例模式的简单功能,供大家交流学习,如有错误欢迎指正.



1
#include <iostream> 2 using std::cout; 3 using std::endl; 4 5 class Singleton 6 { 7 public: 8 static Singleton * getInstance() 9 { 10 if(NULL == _pInstance) 11 { 12 _pInstance = new Singleton; 13 } 14 return _pInstance; 15 } 16 17 static void destory() 18 { 19 if(_pInstance) 20 { 21 delete _pInstance; 22 } 23 } 24 25 private: 26 Singleton(){ cout << "Singleton()" << endl;} 27 ~Singleton(){ cout << "~Singleton()" << endl;} 28 29 private: 30 static Singleton * _pInstance; 31 }; 32 33 Singleton * Singleton::_pInstance = NULL;

 测试用例因人而异,请自行测试.

posted @ 2017-06-16 23:48  m4ch0  阅读(286)  评论(0编辑  收藏  举报