单体模式Singleton

2014-11-24 01:19:36 · 作者: · 浏览: 0

单体模式/***************************************************************************
文件名: Singleton.h
内 容: 单体模式
说 明:
创建日期: 2014年03月14日
创建人:
版权所有:
***************************************************************************/

首先,单例模式是作为对象的创建模式,此外还包括工厂模式。单例模式的三个特点:
1,该类只有一个实例
2,该类自行创建该实例(在该类内部创建自身的实例对象)
3,向整个系统公开这个实例接口


#ifndef _SINGLETON_H
#define _SINGLETON_H

template
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
T& Singleton ::Instance()
{
if(!si_instance)
{
if( !si_instance )
{
if( si_destroyed )
{
si_destroyed = false;
}

si_instance = new T;
}
}

return *si_instance;
}

template
void Singleton ::DestroySingleton()
{
delete si_instance;

si_instance = NULL;
si_destroyed = true;
}

#define INSTANTIATE_SINGLETON(TYPE) \
template class Singleton ; \
template<> TYPE* Singleton ::si_instance = 0; \
template<> bool Singleton >::si_destroyed = false