火焰傀偶的挣扎旅程

纯爷们的一生就是不停地燃烧,keep on burning soul!!
随笔 - 6, 文章 - 5, 评论 - 4, 引用 - 0
数据加载中……

[转]c++通过模板类巧妙实现单件模式的继承

//Singleton.hpp:内容如下 继承使用即可

/*
用例:

class DeviceManager : public Singleton<DeviceManager>
{

   public:
      void ToString() const
      {
   
      printf("Hi, I'm DeviceManager.\n");
      }
};

int _tmain(int argc, _TCHAR* argv[])
{
   DeviceManager::GetInstance()->ToString();
   return 0;
}


*/

#ifndef SINGLETON_H
#define SINGLETON_H

template 
<class T>
class Singleton
{
public:
    
static T* GetInstance()
    {
        
if ( NULL == m_instance )
        {
            m_instance 
= new T;
        }

        
return m_instance;
    }

    
static void ReleaseInstance()
    {
        
if ( NULL != m_instance )
        {
            delete m_instance;
            m_instance 
= NULL;
        }
    }

protected:
    Singleton() {}
    
virtual ~Singleton() {}

private:
    Singleton(
const Singleton&){};
    Singleton
& operator=(const Singleton&){};

private:
    
static T* m_instance;
};

template 
<class T>
T
* Singleton<T>::m_instance = NULL;

#endif

posted on 2012-06-13 16:56 WhiteDummy 阅读(323) 评论(0)  编辑 收藏 引用 所属分类: c/c++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理