Singleton 是对全局变量的取代策略
作用:保证一个类只能有一个实例,并提供一个全局唯一的访问点。
仅有一个实例:通过类的静态成员变量来体现。
提供访问它的全局访问点:访问静态成员变量的静态成员函数来体现。
《设计模式》一书中给出了一种很不错的实现,定义一个单例类,使用类的私有静态指针变量指向类的唯一实例,并用一个公有的静态方法获取该实例。
单例模式通过类本身来管理其唯一实例,这种特性提供了解决问题的方法。唯一的实例是类的一个普通对象,但设计这个类时,让它只能创建一个实例并提供对此实例的全局访问。唯一实例类Singleton在静态成员函数中隐藏创建实例的操作。习惯上把这个成员函数叫做Instance(),它的返回值是唯一实例的指针。
单例类Singleton有以下特征:
它有一个指向唯一实例的静态指针,并且是私有的;
它有一个公有的函数,可以获取这个唯一的实例,并且在需要的时候创建该实例;
上面是标准的 Singleton实现,但是存在如下问题:
添加模板化实现:
实现线程安全:
CresGuard 类主要的功能是线程访问同步,代码如下:
作用:保证一个类只能有一个实例,并提供一个全局唯一的访问点。
仅有一个实例:通过类的静态成员变量来体现。
提供访问它的全局访问点:访问静态成员变量的静态成员函数来体现。
《设计模式》一书中给出了一种很不错的实现,定义一个单例类,使用类的私有静态指针变量指向类的唯一实例,并用一个公有的静态方法获取该实例。
单例模式通过类本身来管理其唯一实例,这种特性提供了解决问题的方法。唯一的实例是类的一个普通对象,但设计这个类时,让它只能创建一个实例并提供对此实例的全局访问。唯一实例类Singleton在静态成员函数中隐藏创建实例的操作。习惯上把这个成员函数叫做Instance(),它的返回值是唯一实例的指针。
单例类Singleton有以下特征:
它有一个指向唯一实例的静态指针,并且是私有的;
它有一个公有的函数,可以获取这个唯一的实例,并且在需要的时候创建该实例;
它的构造函数是私有的,这样就不能从别处创建该类的实例。
在Singleton模式的结构图中可以看到,我们通过维护一个static的成员变量_instance来记录这个唯一的对象实例。通过提供一个staitc的接口Instance来获得这个唯一的实例。
代码如下:
class Singleton
{
public:
static Singleton * Instance()
{
if( 0== _instance)
{
_instance = new Singleton;
}
return _instance;
}
protected:
Singleton(void)
{
}
virtual ~Singleton(void)
{
}
static Singleton* _instance;
};
上面是标准的 Singleton实现,但是存在如下问题:
1.没有实现垃圾回收
2.没有实现模板化,如果有很多类都需要用到Singleton模式,那么每个类都需要这样实现,比较冗余。实现模板化后大大减少工作量
3.上面实现不是多线程安全的
下面针对上面的问题一一解决:
实现垃圾回收:引入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;
添加模板化实现:
#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 >;
}
}
实现线程安全:
但是如果把它用到多线程的程序就会发生问题。主要的问题在于同时执行_instance.reset ( new T); 就会同时产生两个新的对象,然后马上释放一个,这跟Singleton模式的本意不符。所以,需要更加安全的版本:
/********************************************************************
Module: Singleton.h
********************************************************************/
#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();
private:
Singleton(void){}
~Singleton(void){}
Singleton(const Singleton&){}
Singleton & operator= (const Singleton &){}
static auto_ptr<T> _instance;
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()
{
if( 0 == _instance.get() )
{
CResGuard::CGuard gd(_rs);
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 >;
}
}
CresGuard 类主要的功能是线程访问同步,代码如下:
</pre><pre name="code" class="cpp">
/******************************************************************************
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;
};
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
};
Example::实用方法:
ServiceManger实现单件模式的类,就应该这样实现:
#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();
}