#单例模式
- 问题一
为什么单例模式中的单例对象是用static修饰?为什么单例模式中的单例选择用静态成员的方式去实现? - 问题二
这个静态成员变量什么时候被初始化呢?
##问题一
为什么单例模式中的单例对象是用static修饰?为什么单例模式中的单例选择用静态成员的方式去实现?
单例模式的使用方式是:需要采用一种方法,实现这样的一种工具。即未经实例化的去使用一个类。这个要求决定了需要使用静态成员变量来实现单例对象。类的静态成员变量属于类本身,为类的对象所共用,是c++数据共享的一个体现。而且静态变量的初始化是早于
##问题二
这个静态成员变量什么时候被初始化呢?
All static data is initiald to zero when the first object is created, if no other initialization is present. tutorialspoint.com
如果没有出现其他的初始化过程,静态变量会在第一个对象创建出来是被初始化成0。
要点
- 私有构造函数
- 公有静态函数 GetInstance()
- 私有静态成员 __instance
.h文件
class One{
public:
static One* GetInstance();
private:
One(){}
One(One&);
One(const One&);
const One& operator=(One&);
const One& operator=(const One&);
private:
static One* __instance;
};
.cpp文件
One* One::__instance = nullptr;
One* One::GetInstance(){
if (__instance == nullptr)
__instance = new One();
return __instance;
}
宏定义版本
//单例模式声明和实现
#define SINGLETON_DEFINE(CLASS_NAME) public: \
static CLASS_NAME* GetInstance(); \
private: CLASS_NAME(){} \
CLASS_NAME(CLASS_NAME&); \
CLASS_NAME(const CLASS_NAME&); \
const CLASS_NAME& operator=(CLASS_NAME&); \
const CLASS_NAME& operator=(const CLASS_NAME&); \
private: \
static CLASS_NAME* __instance; \
#define SINGLETON_IMPLETE(CLASS_NAME) \
CLASS_NAME* CLASS_NAME::__instance = nullptr; \
CLASS_NAME* CLASS_NAME::GetInstance(){ \
if (CLASS_NAME::__instance == nullptr) \
{CLASS_NAME::__instance = new One();} \
return CLASS_NAME::__instance;} \