单件模式

1. 意图
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
2. 动机
对一些类来说,只有一个实例是很重要的。虽然系统中可以有许多打印机,但却只应该有一个打印假脱机( printer spooler),只应该有一个文件系统和一个窗口管理器。一个数字滤波器只能有一个A / D转换器。一个会计系统只能专用于一个公司。
我们怎么样才能保证一个类只有一个实例并且这个实例易于被访问呢?一个全局变量使得一个对象可以被访问,但它不能防止你实例化多个对象。一个更好的办法是,让类自身负责保存它的唯一实例。这个类可以保证没有其他实例可以被创建(通过截取创建新对象的请求),并且它可以提供一个访问该实例的方法。这就是Singleton模式。
3. 适用性
在下面的情况下可以使用Singleton模式. 当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。 当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。
4. 结构
5. 参与者
Singleton
定义一个GetInstance操作,允许客户访问它的唯一实例。GetInstance是一个类操作(即Smalltalk中的一个类方法和C++中的一个静态成员函数)。可能负责创建它自己的唯一实例。
6. 协作
客户只能通过Singleton的GetInstance操作访问一个Singleton的实例。
7. 效果
Singleton模式有许多优点:
1) 对唯一实例的受控访问因为Singleton类封装它的唯一实例,所以它可以严格的控制客户怎样以及何时访问它。
2) 缩小名空间Singleton模式是对全局变量的一种改进。它避免了那些存储唯一实例的全局变量污染名空间。
3) 允许对操作和表示的精化Singleton类可以有子类,而且用这个扩展类的实例来配置一个应用是很容易的。你可以用你所需要的类的实例在运行时刻配置应用。
4) 允许可变数目的实例这个模式使得你易于改变你的想法,并允许Singleton类的多个实例。此外,你可以用相同的方法来控制应用所使用的实例的数目。只有允许访问Singleton实例的操作需要改变。
5) 比类操作更灵活另一种封装单件功能的方式是使用类操作(即C++中的静态成员函数或者是Smalltalk中的类方法)。但这两种语言技术都难以改变设计以允许一个类有多个实例。
此外,C++中的静态成员函数不是虚函数,因此子类不能多态的重定义它们。
8. 实现
class Singleton
{
static std::auto_ptr<Singleton> m_pInstance;
protected:
//prevent user making our any instance by manually
//构造函数是保护类型的。
Singleton(){}
public:
~Singleton(){}
//Return this singleton class' instance pointer
static Singleton* Instance()
{
if(!m_pInstance.get())
{
m_pInstance = std::auto_ptr<Singleton>(new Singleton());
}
return m_pInstance.get();
}
};
怎样来使用它呢?不要试图从这个类派生你的单件子类,那样的结果是不妥当的,如果你需要多个单件子类,还是使用下面的宏定义更为妥当:
#define DEFINE_SINGLETON(cls)\
private:\
static std::auto_ptr<cls> m_pInstance;\
protected:\
cls(){}\
public:\
~cls(){}\
static cls* Instance(){\
if(!m_pInstance.get()){\
m_pInstance = std::auto_ptr<cls>(new cls());\
}\
return m_pInstance.get();\
}
#define IMPLEMENT_SINGLETON(cls) \
std::auto_ptr<cls> cls::m_pInstance(NULL);
假定你需要实现一个单件类YY,这样书写:
class YY
{
DEFINE_SINGLETON(YY);
public:
//your interfaces here...
};
在cpp文件中,书写:
IMPLEMENT_SINGLETON(YY);
需要引入这个类的实例的时候,使用这样的语句:
YY* pYY = YY::Instance();
这,就是全部。
如果需要定义其他的单件类,重复上面的定义,就可以了。
当想集中管理一个应用程序所需的所有配置时,可以声明一个CToolsOptions的类,其中包含配置属性集合。对于这个类的实例,显然是一个实例就够了;当编写绘图程序时,考虑绘制矩形,圆形等分别使用CGraphTool派生的工具类,每个派生类负责处理具体的绘制动作和相关的UI相应逻辑。这些工具类典型的在被用户选择工具栏的图元按钮时被选中。依照这种模式,你应该对所有的图元工具从事注册工作,使得绘图程序了解运行时刻可以使用那些图元工具。同样的,负责管理注册信息的这个管理器也只需要一个实例就行了。

 

 

 

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();



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 类主要的功能是线程访问同步,代码如下:

/******************************************************************************

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

};





///////////////////////////////////////////////////////////////////////////////

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++了不起。



posted @   jackyxm  阅读(505)  评论(1编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示