单体模式Singleton



单体模式/***************************************************************************
文件名:  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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值