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类,我都要实现上面这一切,这让我觉得烦死了。于是我想到了模板来完成这些重复的工作。
现在我们要添加本文中最吸引人单件实现:
#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模式的本意不符。所以,你需要更加安全的版本:
#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 类主要的功能是线程访问同步,代码如下:
#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++了不起。
C++完美实现Singleton模式[转]的更多相关文章
- 转:Singleton模式
C++完美实现Singleton模式 转自:http://www.cppblog.com/dyj057/archive/2005/09/20/346.html boost库的Singleton的实现 ...
- 面试:用 Java 实现一个 Singleton 模式
面试:用 Java 实现一个 Singleton 模式 面试系列更新后,终于迎来了我们的第一期,我们也将贴近<剑指 Offer>的题目给大家带来 Java 的讲解,个人还是非常推荐< ...
- 剑指offer之面试题2:实现Singleton模式
来源:剑指offer 这篇主要记录<剑指offer>书籍中的面试题2:实现Singleton模式 使用语言:C# 代码环境:VS2017 总共有5中解法,从前往后依次优化. 结构如下: 前 ...
- 6、单例模式 Singleton模式 只有一个实例 创建型模式
1.了解Singleton模式 程序在运行时,通常都会生成很多实例.例如,表示字符串的java . lang . string类的实例与字符串是- -对- -的关系,所以当有1000个字符串的时候,会 ...
- Qt 中使用Singleton模式需小心
在qt中,使用Singleton模式时一定要小心.因为Singleton模式中使用的是静态对象,静态对象是直到程序结束才被释放的,然而,一旦把该静态对象纳入了Qt的父子对象体系,就会导致不明确的行为. ...
- 剑指Offer面试题:1.实现Singleton模式
说来惭愧,自己在毕业之前就该好好看看<剑指Offer>这本书的,但是各种原因就是没看,也因此错过了很多机会,后悔莫及.但是后悔是没用的,现在趁还有余力,把这本书好好看一遍,并通过C#通通实 ...
- C++ Singleton模式
地址:http://www.cppblog.com/dyj057/archive/2005/09/20/346.html Singleton模式是常用的设计模式之一,但是要实现一个真正实用的设计模式却 ...
- Singleton模式——对象创建型模式
Singleton模式即为单例模式/单件模式. (一)意图--保证一个类仅有一个实例,并提供一个访问它的全局访问点. 如一台计算机可以有多个端口,但是应该统一管理这些端口,避免访问冲突.--选择Sin ...
- Singleton模式和Mono-State模式
类和实例 对于大多数的类,都可以创建多个实例.在需要和不需要时,创建和删除这些实例.该过程会伴随着内存的分配和归还. 同时,有一些类,应该仅有一个实例.该实例在程序启动/结束时被创建和删除. root ...
随机推荐
- 第八篇:python基础_8 面向对象与网络编程
本篇内容 接口与归一化设计 多态与多态性 封装 面向对象高级 异常处理 网络编程 一. 接口与归一化设计 1.定义 (1)归一化让使用者无需关心对象的类是什么,只需要知道这些对象都具备某些功能就可以了 ...
- hdu 1969 Pie (二分法)
Pie Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submiss ...
- POJ 2828 Buy Tickets | 线段树的喵用
题意: 给你n次插队操作,每次两个数,pos,w,意为在pos后插入一个权值为w的数; 最后输出1~n的权值 题解: 首先可以发现,最后一次插入的位置是准确的位置 所以这个就变成了若干个子问题, 所以 ...
- HDU 5752
Sqrt Bo Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total S ...
- SQL的主键和外键的作用
SQL的主键和外键约束 转载自:http://www.cnblogs.com/ywb-lv/archive/2012/03/12/2391860.html感谢原文作者的总结 SQL的主键和外键的作用: ...
- mysql 导入
1.默认情况下:MySQL导入文件大小有限制的,最大为2M,所以当文件很大时候,直接无法导入,可修改php.ini参数调整: 在php.ini中修改相关参数: 影响MySQL导入文件大小的参数有三个: ...
- 微信设置URL之WebApi方式
微信公众号开发者设置里的URL,现在采用WebAPI的方式,结果一直报“未能正确设置Token”的错误,采用Handler和MVC的方式倒是可以. 解决步骤一,添加服务器IP到白名单. 解决步骤二,确 ...
- 洛谷 P2916 [USACO08NOV]为母牛欢呼Cheering up the C…
题目描述 Farmer John has grown so lazy that he no longer wants to continue maintaining the cow paths tha ...
- (十)Linux查看系统信息的一些命令及查看已安装软件包的命令
转自:http://cheneyph.iteye.com/blog/824746 系统 # uname -a # 查看内核/操作系统/CPU信息 # head -n 1 /etc/issue # 查看 ...
- UCRT: VC 2015 Universal CRT, by Microsoft
https://blogs.msdn.microsoft.com/vcblog/2015/03/03/introducing-the-universal-crt/ App local UCRT DLL ...