#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>
#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>
{
}
在需要是单例模式的类中,继承单例,把需要的类作为参数就行了;
QuestManager::getInstance();
本文介绍了一种使用C++模板元编程实现单例模式的方法。通过定义一个通用的Singleton基类,使得任何类都能方便地转换为单例模式。这种实现方式简洁且易于使用。

3462

被折叠的 条评论
为什么被折叠?



