C++ 使用模版范式写一个单例模式的类--简单实现单例模式

#ifndef __SINGLETON__
#define __SINGLETON__


#include "stdafx.h"


template <class T>
class Singleton
{
public:
static T* getInstance(){
if(_instance == NULL)
{
_instance = new T;
}
return _instance;
}


static void Release()
{
if(_instance != NULL)
{
delete _instance;
_instance = NULL;
}
}
protected:
Singleton(void){}   


virtual ~Singleton(void){}


static T* _instance;
};
template <class T> T* Singleton<T>::_instance = NULL;

#endif  //__SINGLETON__


使用方法:

class QuestManager:public Singleton<QuestManager>
{


在需要是单例模式的类中,继承单例,把需要的类作为参数就行了;





你可能感兴趣的:(C++ 使用模版范式写一个单例模式的类--简单实现单例模式)