单体模式/***************************************************************************
文件名: Singleton.h
内 容: 单体模式
说 明:
创建日期: 2014年03月14日
创建人:
版权所有:
***************************************************************************/
首先,单例模式是作为对象的创建模式,此外还包括工厂模式。单例模式的三个特点:
1,该类只有一个实例
2,该类自行创建该实例(在该类内部创建自身的实例对象)
3,向整个系统公开这个实例接口
#ifndef _SINGLETON_H
#define _SINGLETON_H
template <typename T>
class Singleton
{
public:
static T& Instance();
protected:
Singleton() {};
private:
Singleton(const Singleton &);
Singleton& operator=(const Singleton &);
static void DestroySingleton();
static T *si_instance;
static bool si_destroyed;
};
#endif // _SINGLETON_H
#include "Singleton.h"
template<typename T>
T& Singleton<T>::Instance()
{
if(!si_instance)
{
if( !si_instance )
{
if( si_destroyed )
{
si_destroyed = false;
}
si_instance = new T;
}
}
return *si_instance;
}
template<typename T>
void Singleton<T>::DestroySingleton()
{
delete si_instance;
si_instance = NULL;
si_destroyed = true;
}
#define INSTANTIATE_SINGLETON(TYPE) \
template class Singleton<TYPE>; \
template<> TYPE* Singleton<TYPE>::si_instance = 0; \
template<> bool Singleton<TYPE> >::si_destroyed = false
原文:http://blog.csdn.net/zhanghefu/article/details/21302059