单例模式
2015-04-27 11:46 foolbread-老陈 阅读(101) 评论(0) 编辑 收藏 举报单例模式:确保一个类只有一个实例,并提供全局访问点。——《HEAD FIRST 设计模式》
我的c++代码:
#ifndef DESIGN_SINGLETON_H_ #define DESIGN_SINGLETON_H_ #include <iostream> class Singleton { private: Singleton(){} public: static Singleton* GetInstance(); private: static Singleton* g_instance; }; #endif // DESIGN_SINGLETON_H_
#include "singleton.h" Singleton* Singleton::g_instance = new Singleton(); Singleton* Singleton::GetInstance() { if (g_instance == 0) { std::cout << "singleton initing..." << std::endl; g_instance = new Singleton(); } return g_instance; }