首页 > 其他 > 详细

单体模式Singleton

时间:2014-03-16 14:05:48      阅读:395      评论:0      收藏:0      [点我收藏+]


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


单体模式Singleton,布布扣,bubuko.com

单体模式Singleton

原文:http://blog.csdn.net/zhanghefu/article/details/21302059

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!