存在的问题
写程序的时候经常需要用到单例模式。而写一个单例类,我们经常要这么些
class A {
public:
A* Instance();
void DelInst();
private:
static A* pInst;
A();
~A();
A(A& obj);
A& operator=(A& obj);
}
每一个类都写这些重复的东西,违反了DRY(Don't repeat yourself)原则
目标:
目标是减少重复, 那如何减少重复呢?
以知量:
首先来看单例模式类的两个要素:
要素1: 构造函数、拷贝构造函数,赋值运算符重载,析构函数必须声明为私有。
要素2: 然后必须提供获取单例,销毁单例的 Instance() 、 DelInst()接口。以及保存单例的指针
C++中复用的方式有哪些?
函数、继承、模板、宏(还有其他的吗?)
约束条件
要素1中, 一个类的构造函数等等,必须在自己声明,不能通过继承的方式从父类获得。那么应该怎么做呢?下面会看到,通过定义一个宏,来减少重复的声明。
要素2中,的Instance()接口可以在父类当中继承获得。由于这些接口要适应不同的类型,所以父类需要是一个模板类
解决方式
可以考虑使用一个单例模板类加宏定义的方式
#pragma once
//单例模板类 template<typename T> class SinInstTmp{ public: static T* Inst() { if (pInst == NULL) { try { pInst = new T(); } catch(...) { pInst = NULL; } } return pInst; } static void DelInst() { if (pInst) { delete pInst; pInst = NULL; } } private: static T* pInst; }; template<typename T> T* SinInstTmp<T>::pInst = NULL;
//宏定义
//the concrete class must declare construction and destruction fun to be private //must have parameter-free construction #define DeclareSingleton(ClassName) \ friend SinInstTmp<ClassName>; \ private: \ ClassName(); \ ~ClassName(); \ ClassName(ClassName& obj); \ ClassName& operator=(ClassName& obj);
class SubType : public SinInstTmp<SubType>{ public:
void Interface1();
void Interface2(); DeclareSingleton(SubType) }
SubType::Inst()->Interface1(); SubType::Inst()->Interface2();