标签:des style class blog code color
单件模式即在整个应用程序中只有一个类实例且这个实例所占资源在整个应用程序中是共享的。
#include <iostream> class CSingleton { private: CSingleton() { std::cout<<"Singleton Constructed."<<std::endl; } CSingleton(const CSingleton&){}; void operator =(const CSingleton&){}; static CSingleton * _instance; class CGarbo { public: ~CGarbo() { if (CSingleton::_instance) { delete CSingleton::_instance; std::cout<<"~CGarbo():Singleton Instance Deleted."<<std::endl; } CSingleton::_instance = NULL; } }; friend class CGarbo; public: ~CSingleton() { std::cout<<"~CSingleton():Singleton Destructed."<<std::endl; } static CSingleton * instance() { if(!_instance) { _instance = new CSingleton(); static CGarbo _garbo; } return _instance; } ////for test void test(){ std::cout<<"TEST()"<<std::endl; } }; CSingleton *CSingleton::_instance=NULL; int main() { CSingleton::instance() ->test(); return 0; }
使用宏定义实现的好处在于:
1、代码更清晰;
2、当一个系统中需要用到多个单件模式的实例时,可重用代码;
#include <iostream> #define PATTERN_SINGLETON_DECLARE(classname) private: static classname * _instance; class CGarbo { public: ~CGarbo() { if (classname::_instance) { delete classname::_instance; std::cout<<"~CGarbo():Singleton Instance Deleted."<<std::endl; } classname::_instance = NULL; } }; friend class CGarbo; public: static classname* instance(); #define PATTERN_SINGLETON_IMPLEMENT(classname) classname * classname::_instance=NULL; classname * classname::instance() { if(!_instance) { _instance = new classname(); static CGarbo _garbo; } return _instance; } class CSingleton { PATTERN_SINGLETON_DECLARE(CSingleton); private: CSingleton() { std::cout<<"Singleton Constructed."<<std::endl; } CSingleton(const CSingleton&){}; void operator =(const CSingleton&){}; public: ~CSingleton() { std::cout<<"~CSingleton():Singleton Destructed."<<std::endl; } ////for test void test(){ std::cout<<"TEST()"<<std::endl; } }; //全局共享,所有接口均通过该宏来访问 #define g_Singleton (*CSingleton::instance()) PATTERN_SINGLETON_IMPLEMENT(CSingleton); int main() { g_Singleton.test(); return 0; }具体实现时,以下部分一般在cpp文件中实现,其他在.h中进行声明:
PATTERN_SINGLETON_IMPLEMENT(CSingleton); int main() { g_Singleton.test(); return 0; }
C++ 单件模式实现及对象释放,布布扣,bubuko.com
标签:des style class blog code color
原文地址:http://blog.csdn.net/sloan6/article/details/29827861