C++中的单例模板类

存在的问题

写程序的时候经常需要用到单例模式。而写一个单例类,我们经常要这么些

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
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
T* SinInstTmp::pInst = NULL;

//宏定义
//the concrete class must declare construction and destruction fun to be private
//must have parameter-free construction
#define DeclareSingleton(ClassName)	\
	friend SinInstTmp;		\
private:			\
ClassName();		\
~ClassName();		\
ClassName(ClassName& obj);	\
ClassName& operator=(ClassName& obj);	


于是,所有的单例类都可以如下声明:
class SubType : public SinInstTmp{
public:
    	void Interface1();
    	void Interface2();
    	DeclareSingleton(SubType)
}


使用的时候像这样就可以了
SubType::Inst()->Interface1();
SubType::Inst()->Interface2();

你可能感兴趣的:(C++)