地址:http://www.cppblog.com/dyj057/archive/2005/09/20/346.html

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

}

C++ Singleton模式的更多相关文章

  1. Qt 中使用Singleton模式需小心

    在qt中,使用Singleton模式时一定要小心.因为Singleton模式中使用的是静态对象,静态对象是直到程序结束才被释放的,然而,一旦把该静态对象纳入了Qt的父子对象体系,就会导致不明确的行为. ...

  2. 剑指Offer面试题:1.实现Singleton模式

    说来惭愧,自己在毕业之前就该好好看看<剑指Offer>这本书的,但是各种原因就是没看,也因此错过了很多机会,后悔莫及.但是后悔是没用的,现在趁还有余力,把这本书好好看一遍,并通过C#通通实 ...

  3. Singleton模式——对象创建型模式

    Singleton模式即为单例模式/单件模式. (一)意图--保证一个类仅有一个实例,并提供一个访问它的全局访问点. 如一台计算机可以有多个端口,但是应该统一管理这些端口,避免访问冲突.--选择Sin ...

  4. Singleton模式和Mono-State模式

    类和实例 对于大多数的类,都可以创建多个实例.在需要和不需要时,创建和删除这些实例.该过程会伴随着内存的分配和归还. 同时,有一些类,应该仅有一个实例.该实例在程序启动/结束时被创建和删除. root ...

  5. 转:Singleton模式

    C++完美实现Singleton模式  转自:http://www.cppblog.com/dyj057/archive/2005/09/20/346.html boost库的Singleton的实现 ...

  6. Singleton模式

    Singleton模式的特点: 保证一个类仅有一个实例,并提供一个访问它的全局访问点. 定义一个Instance操作,允许客户访问它的唯一实例.Instance是一个类操作(C++中的一个静态成员函数 ...

  7. Objective-C的singleton模式

    最近因为在ios应用开发中,考虑到一些公共方法的封装使用,就决定使用单例模式的写法了..不知道,Object-c中的单例模式的写法是否和java中的写法是否有所区别?于是阿堂从网上一搜,发现“ Obj ...

  8. js中singleton模式解析及运用

    singleton模式,又名单例模式.顾名思义,就是只能实例化一次的类(javascript中没有真正的类,我们通常用函数来模拟类,习惯称之为"伪类").具体地说,singleto ...

  9. Singleton 模式

    个人认为 Singleton 模式是设计模式中最为简单.最为常见.最容易实现,也是最应该熟悉和掌握的模式.且不说公司企业在招聘的时候为了考察员工对设计的了解和把握,考的最多的就是 Singleton ...

随机推荐

  1. GNU CMAKE 笔记

    最近在调试OJ, 忙了4天多, 最后的问题是judge模块不能正常工作. judge 模块就是两个C++源文件, 它的工作是 从数据库获取用户提交的源码 测评 将测评结果写到数据库 测评部分是与数据库 ...

  2. Centos7更新firefox

    1.用你本地的旧版 firefox,访问http://www.firefox.com.cn,下载Linux版本的Firefox. 2.进入存放下载文件(Firefox-latest-x86_64.ta ...

  3. ARPSpoofing教程(二) - 获取网络设备中的详细地址信息

    WinPcap中文API  http://www.ferrisxu.com/WinPcap/html/index.html 1: #include"pcap.h" 2: #incl ...

  4. hdu 2014 青年歌手大奖赛_评委会打分

    题意: 输入N个数,去掉最大和最小的数,求剩余的数的平均数. 解法: 找到分别最大和最小的数,然后从总和中减去他们,再求平均数(不要排序): 1: #include<stdlib.h> 2 ...

  5. 常见linux命令释义(第四天)——bash部分

    学linux的时候,我跳过了一些很重要的东西.比如分区.还有vim的深入学习.分区没有学习是因为我装的是虚拟机,不知道是什么原因,格式化分区不能正常显示.至于vim,简单的增删改查我已经了解了.能够顺 ...

  6. DNS(二)之bind的视图功能

    bind视图工作原理 在我国目前的网络环境下面,多个运营商并存,运营商之间的存在一定的网络互通问题,如果把来自不同的运营商或者地域的所有用户通过简单的A记录分配到一个机房,那么就存在部分网民访问延时大 ...

  7. shell 中 &&和||的方法

    Shell && 和 || shell 在执行某个命令的时候,会返回一个返回值,该返回值保存在 shell 变量 $? 中.当 $? == 0 时,表示执行成功:当 $? == 1 时 ...

  8. 数据库中Count是什么意思和SUM有什么区别?

    今天早上在做数据库的练习, 我是这样写的: 得出是: 后来才知道是: 结果是: 后来我意识到区别,于是查资料得到: 数据库中的count,是用来统计你查询出来的记录数,比如学生表中有十条记录:sele ...

  9. 【转】七种常见阈值分割代码(Otsu、最大熵、迭代法、自适应阀值、手动、迭代法、基本全局阈值法)

    http://blog.csdn.net/xw20084898/article/details/17564957 一.工具:VC+OpenCV 二.语言:C++ 三.原理 otsu法(最大类间方差法, ...

  10. WinForm------GridControl右键添加动态菜单

    转载:http://www.devexpresscn.com/Resources/Documentation-440.html 更加好用的方法: 1.添加一个GridControl控件,PopupMe ...