C++完美实现Singleton模式

Singleton模式是常用的设计模式之一,但是要实现一个真正实用的设计模式却也不是件容易的事情。

1.         标准的实现

class Singleton
{
public:
       static Singleton * Instance()
       {
              if( 0== _instance)
              {
                     _instance = new Singleton;
              }
              return _instance;
       }
protected:
       Singleton(void)
       {
       }
       virtual ~Singleton(void)
       {
       }
       static Singleton* _instance;
};


       这是教科书上使用的方法。看起来没有什么问题,其实包含很多的问题。下面我们一个一个的解决。

2.         自动垃圾回收

上面的程序必须记住在程序结束的时候,释放内存。为了让它自动的释放内存,我们引入auto_ptr改变它。

#include <memory>
#include <iostream>
using namespace std;
class Singleton
{
public:
       static Singleton * Instance()
       {
              if( 0== _instance.get())
              {
                     _instance.reset( new Singleton);
              }
              return _instance.get();
       }
protected:
       Singleton(void)
       {
              cout <<"Create Singleton"<<endl;
       }
       virtual ~Singleton(void)
       {
              cout << "Destroy Singleton"<<endl;
       }
       friend class auto_ptr<Singleton>;
       static auto_ptr<Singleton> _instance;
};
//Singleton.cpp
auto_ptr<Singleton> Singleton::_instance;


3.         增加模板

在我的一个工程中,有多个的Singleton类,对Singleton类,我都要实现上面这一切,这让我觉得烦死了。于是我想到了模板来完成这些重复的工作。

现在我们要添加本文中最吸引人单件实现:

/********************************************************************
    (c) 2003-2005 C2217 Studio
    Module:    Singleton.h
    Author:     Yangjun D.
    Created:    9/3/2005   23:17
    Purpose:    Implement singleton pattern
    History:
*********************************************************************/
#pragma once
 
#include <memory>
using namespace std;
using namespace C2217::Win32;
 
namespace C2217
{
namespace Pattern
{
template <class T>
class Singleton
{
public:
       static inline T* instance();
      
private:
       Singleton(void){}
       ~Singleton(void){}
       Singleton(const Singleton&){}
       Singleton & operator= (const Singleton &){}
 
       static auto_ptr<T> _instance;
};
 
template <class T>
auto_ptr<T> Singleton<T>::_instance;
 
template <class T>
 inline T* Singleton<T>::instance()
{
       if( 0== _instance.get())
       {
              _instance.reset ( new T);
       }
      
       return _instance.get();
}
 
//Class that will implement the singleton mode,
//must use the macro in it's delare file
#define DECLARE_SINGLETON_CLASS( type ) \
       friend class auto_ptr< type >;\
       friend class Singleton< type >;
}
}
 


4.         线程安全

上面的程序可以适应单线程的程序。但是如果把它用到多线程的程序就会发生问题。主要的问题在于同时执行_instance.reset ( new T); 就会同时产生两个新的对象,然后马上释放一个,这跟Singleton模式的本意不符。所以,你需要更加安全的版本:

/********************************************************************
    (c) 2003-2005 C2217 Studio
    Module:    Singleton.h
    Author:     Yangjun D.
    Created:    9/3/2005   23:17
    Purpose:    Implement singleton pattern
    History:
*********************************************************************/
#pragma once
 
#include <memory>
using namespace std;
#include "Interlocked.h"
using namespace C2217::Win32;
 
namespace C2217
{
namespace Pattern
{
template <class T>
class Singleton//这个类管理要创建实例的类
{
public:
       static inline T* instance();//是个静态方法 主线程调用的时候也是直接    类名::instance()  这就说明这个方法是只有一个  独有的资源 多线程调用这个instance  都是访问的这一个  只有这个!!
      
private:
       Singleton(void){}
       ~Singleton(void){}
       Singleton(const Singleton&){}
       Singleton & operator= (const Singleton &){}
 
       static auto_ptr<T> _instance;//智能指针 里面存放了 这里new T 的一个指针 需要释放时 会自动释放
       static CResGuard _rs;//由程序来释放全局静态变量和栈里的变量    只有堆里的才是我们自己释放  类的静态成员变量一直存在 他是类的 不是实例的 只有实例的才会跟随实例而完蛋  关键段只能初始化一个 
};
 
template <class T>
auto_ptr<T> Singleton<T>::_instance;//只有在外层才能初始化 
 
template <class T>
CResGuard Singleton<T>::_rs;//调用构造函数 创建一个关键段
 
template <class T>
 inline T* Singleton<T>::instance()//每次就只能调用这个 来创建一个实例  因为他的构造函数重载了默认构造函数 而且重载后的函数只放在protect下面  所以不能malloc 
{
       if( 0 == _instance.get() )//只有没有这个类的实例的情况下才会进入新建实例一个
       {
              //每次调用下面的 因为在CGuard里面有一个CResGuard 的成员变量  于是乎就当前线程初始化了一个关键段了 
              CResGuard::CGuard gd(_rs);//这个是个内嵌类 当这个instance的函数运行完 他也就释放,释放就会调用里面的离开关键段代码  另外一个作用是类似于例子:创建一个树类  又想创建一个树杈类 但是另外起一个类名字 容易混淆又不好看 就可以在类里面声明一个类 类似于命名空间 分辨树类里的树杈或者树脂类等类 而且最后一个作用是如果不用他 而是直接用外围类  那么问题来了 两个线程 都同时初始化一个关键段在同一个地方 就出错了 只能有一个初始化 所以要把先静态初始化好关键段 完后两个线程访问这里的时候 肯定会有一个先进入关键段边界 此时另外一个 等待 而且如果用公用方法调用太麻烦 比如a.进入边界 a.离开边界 太费事 实例调用方法没有类块 性能高
              if( 0== _instance.get())
              {
                     _instance.reset ( new T);//智能指针 里面存放了 这里new T 的一个指针 需要释放时 会自动释放
              }
       }
       return _instance.get();
}
 
//Class that will implement the singleton mode,
//must use the macro in it's delare file
#define DECLARE_SINGLETON_CLASS( type ) \//一个宏而已 也可以放到外面 其他地方
       friend class auto_ptr< type >;\
       friend class Singleton< type >;
}
}
       CresGuard 类主要的功能是线程访问同步,代码如下:
/******************************************************************************
Module:  Interlocked.h
Notices: Copyright (c) 2000 Jeffrey Richter
******************************************************************************/
 
 
#pragma once
///
 
// Instances of this class will be accessed by multiple threads. So,
// all members of this class (except the constructor and destructor)
// must be thread-safe.
//注意在上面那个类的面
class CResGuard {
public:
   CResGuard()  { m_lGrdCnt = 0; InitializeCriticalSection(&m_cs); }
   ~CResGuard() { DeleteCriticalSection(&m_cs); }
 
   // IsGuarded is used for debugging
   BOOL IsGuarded() const { return(m_lGrdCnt > 0); }
 
public:
   class CGuard {
   public:
      CGuard(CResGuard& rg) : m_rg(rg) { m_rg.Guard(); };//调用外围类的进入边界方法 隐藏了外围类的这个方法 更安全 
      ~CGuard() { m_rg.Unguard(); }
 
   private:
      CResGuard& m_rg;//关键地方 CGUard销毁的时候 他会被销毁 以为内他在线程栈上  从而调用析构函数 销毁关键段 
   };
 
private:
   void Guard()   { EnterCriticalSection(&m_cs); m_lGrdCnt++; }
   void Unguard() { m_lGrdCnt--; LeaveCriticalSection(&m_cs); }
 
   // Guard/Unguard can only be accessed by the nested CGuard class.
   friend class CResGuard::CGuard;
 
private:
   CRITICAL_SECTION m_cs;
   long m_lGrdCnt;   // # of EnterCriticalSection calls
};


 

 

///

5.         实用方法

比如你有一个需要实现单件模式的类,就应该这样实现:

#pragma once
#include "singleton.h"
using namespace C2217::Pattern;
 
class ServiceManger
{
public:
       void Run()
       {
       }
private:
       ServiceManger(void)
       {
       }
       virtual ~ServiceManger(void)
       {
       }
       DECLARE_SINGLETON_CLASS(ServiceManger);
};
 
typedef Singleton<ServiceManger> SSManger;
 
//在使用的时候很简单,跟一般的Singleton实现的方法没有什么不同。
int _tmain(int argc, _TCHAR* argv[])
{
        SSManger::instance()->Run();//再调用就会返回上次的
}


 

一个简单的Singleton模式的实现,可以看到C++语言背后隐藏的丰富的语意,我希望有人能实现一个更好的Singleton让大家学习。我从一开始实现Singleton类的过程,其实就是我学习C++的过程,越是深入越觉得C++了不起。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值