单例模式(Singleton Pattern)是设计模式中的一种,它用来保证系统中最多只能存在一个它的实例,其做法是由类自身来创建和持有它的对象实例,把对实例的创建权和管理权都控制在自己手中,以便控制实例数目。

关于如何在C++中实现单例模式的讨论已经太多了,我只是简单介绍一下可以继承的单例类。

首先介绍一下通常所见的单例类的写法,不妨设这个类叫做Singleton。

Singleton.h:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#ifndef _SINGLETON_H_
#define _SINGLETON_H_ #include <memory> class Singleton
{
public:
static Singleton& GetInstance(); private:
Singleton();
~Singleton(); // Use auto_ptr to make sure that the allocated memory for instance
// will be released when program exits (after main() ends).
static std::auto_ptr<Singleton> s_instance;
friend class std::auto_ptr<Singleton>; Singleton(const Singleton&);
Singleton& operator =(const Singleton&);
}; #endif

Singleton.cpp:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include "Singleton.h"
#include <iostream>
#include <boost/thread.hpp> using namespace std;
using namespace boost; auto_ptr<Singleton> Singleton::s_instance; Singleton::Singleton()
{
cout << "Construct Singleton" << endl;
} Singleton::~Singleton()
{
cout << "Destruct Singleton" << endl;
} Singleton& Singleton::GetInstance()
{
static mutex s_mutex;
if (s_instance.get() == NULL)
{
mutex::scoped_lock lock(s_mutex);
if (s_instance.get() == NULL)
{
s_instance.reset(new Singleton());
}
// 'lock' will be destructed now. 's_mutex' will be unlocked.
}
return *s_instance;
}

这个类写的也不完美啦,比如双重判定也会有失效的时候,不过凑合用吧,哈哈。不过话说boost库里也有singleton,我为什么要自己写个呢,无奈地飘过。

废话不多说了,上面的单例类基本上解决了多线程安全问题、实例内存自动释放问题,算是一段可以使用的程序。不过如果系统中有大量单例类(这时候也得好好考虑一下design有没有问题),每个都要这么写一番岂不是很麻烦?要是可以写一个单例基类,以后再创造单例类的时候直接继承一下多方便啊。不过很明显的问题就在那个static对象指针,这个用来保存唯一实例的静态变量如果定义在基类里面,那所有的子类都只能用这同一个变量来保存它们各自的实例了,社会主义国家总得让每个子类都过上温饱生活吧!

以前的时候我还真不知道该怎么解决这个问题,但05年用了WTL(Windows Template Library)之后,我才意识到模板类可以帮助我(话说我真的是自己想到的,虽然现在搜一下能搜到一大堆)。这里要用的还不是普通的模板类,而是像ATL、WTL里面那样把要定义的类自身放入模板参数中,形如class MyClass : public Base<MyClass> { };。这样做有很多优点啦,最显著的比如不需要虚表(节省内存哦)、多态函数的调用在编译时就确定了(既加快了运行速度,也有利于编译器对代码进行优化)。

不妨把这个单例基类叫做ISingleton吧,看起来好像是个interface呢。代码如下:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#ifndef _ISingleton_H_
#define _ISingleton_H_ #include <memory>
#include <boost/thread.hpp> template <typename T>
class ISingleton
{
public:
static T& GetInstance()
{
static boost::mutex s_mutex;
if (s_instance.get() == NULL)
{
boost::mutex::scoped_lock lock(s_mutex);
if (s_instance.get() == NULL)
{
s_instance.reset(new T());
}
// 'lock' will be destructed now. 's_mutex' will be unlocked.
}
return *s_instance;
} protected:
ISingleton() { }
~ISingleton() { } // Use auto_ptr to make sure that the allocated memory for instance
// will be released when program exits (after main() ends).
static std::auto_ptr<T> s_instance; private:
ISingleton(const Singleton&);
ISingleton& operator =(const ISingleton&);
}; template <typename T>
std::auto_ptr<T> ISingleton<T>::s_instance; #endif

要利用ISingleton创建一个自己的单例类,比如MySingleton,可以使用如下的代码:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "Singleton.h"
#include "ISingleton.h"
#include <iostream> using namespace std; class MySingleton : public ISingleton<MySingleton>
{
public:
// blah blah private:
MySingleton()
{
cout << "Construct MySingleton" << endl;
} ~MySingleton()
{
cout << "Destruct MySingleton" << endl;
} friend ISingleton<MySingleton>;
friend class auto_ptr<MySingleton>; MySingleton(const MySingleton&);
MySingleton& operator =(const MySingleton&);
};

最最重要的,千万不要忘了把MySingleton的构造和析构函数弄成private的,还要添加两个友元。有人说ISingleton和MySingleton的析构函数都要加virtual,我倒是觉得没有必要呢,你说呢?另外要注意,MySingleton不能被继承哦。

可以继承的C++ Singleton基类的更多相关文章

  1. 【转载】 C++多继承中重写不同基类中相同原型的虚函数

    本篇随笔为转载,原文地址:C++多继承中重写不同基类中相同原型的虚函数. 在C++多继承体系当中,在派生类中可以重写不同基类中的虚函数.下面就是一个例子: class CBaseA { public: ...

  2. 自定义继承于Page的基类

    自定义继承于Page的基类:MyBasePage[校验用户是否登录,如果登录则获取用户信息,否则跳转到登录页面]============================================ ...

  3. C++ 类的继承六(多继承的二义性--虚基类)

    //多继承的二义性--虚基类(了解为主) #include<iostream> using namespace std; /* 多继承在现在的项目开发中一般不使用,他会增加项目的复杂度 * ...

  4. C++可继承的单例基类模板

    目录 一.介绍 二.代码 三.关键处 五.参考资料 一.介绍 最近在写一个项目,其中用到好几个单例,类本身的设计不是很复杂,但是如果每个都写一遍单例又觉得有点冗余:所以查资料写了一个单例基类模板,只要 ...

  5. PythonI/O进阶学习笔记_3.2面向对象编程_python的继承(多继承/super/MRO/抽象基类/mixin模式)

    前言: 本篇相关内容分为3篇多态.继承.封装,这篇为第二篇 继承. 本篇内容围绕 python基础教程这段: 在面向对象编程中,术语对象大致意味着一系列数据(属性)以及一套访问和操作这些数据的方法.使 ...

  6. C++ Pirmer : 第十五章 : 面向对象程序设计之基类和派生的定义、类型转换与继承与虚函数

    基类和派生类的定义以及虚函数 基类Quote的定义: classs Quote { public: Quote() = default; Quote(cosnt std::string& bo ...

  7. C++ (P160—)多继承 二义性 虚基类 “向上转型”

    1 多继承中,必须给每个基类指定一种派生类型,如果缺省,相应的基类则取私有派生类型,而不是和前一个基类取相同的派生类型 2 一个类的保护成员只能被本类的成员函数或者它的派生类成员函数访问 3 由于c+ ...

  8. C++学习之路—继承与派生(一):基本概念与基类成员的访问属性

    (本文根据<c++程序设计>(谭浩强)总结而成,整理者:华科小涛@http://www.cnblogs.com/hust-ghtao,转载请注明) 1   基本思想与概念 在传统的程序设计 ...

  9. WPF 之 创建继承自Window 基类的自定义窗口基类

    开发项目时,按照美工的设计其外边框(包括最大化,最小化,关闭等按钮)自然不同于 Window 自身的,但窗口的外边框及窗口移动.最小化等标题栏操作基本都是一样的.所以通过查看资料,可按如下方法创建继承 ...

随机推荐

  1. 通过读取配置文件App.config来获取数据库连接字符串

    有两种方式://通过读取配置文件来获取连接字符串 第一种方式: App.config 文件的格式: <?xml version="1.0" encoding="ut ...

  2. TM4C123GH6PM程序

    模式一&模式二:单次计时&周期计时/******************************************* 开发坏境:CCSv5.4 开发板:TIVA C Launch ...

  3. asp.net C#检查URL是否有效

    我们有时候需要对用户输入的网站(URL)进行有效性检查,  代码如下 复制代码 function CheckUrl(str) {    var RegUrl = new RegExp();    Re ...

  4. jQuery 自定义事件的学习笔记

    jquery中提供了两种方法可以绑定自定义事件: bind()和one()而绑定的自定义事件的触发,必须得用jquery中的trigger()方法才能触发. 我们先来看on事件  代码如下 复制代码 ...

  5. HOWTO: Be more productive

    ---by   Aaron Swartz HOWTO: Be more productive “With all the time you spend watching TV,” he tells m ...

  6. XML解析的例子

    ////  main.m//  homewoek////  Created by hehe on 15/9/9.//  Copyright (c) 2015年 wang.hehe. All right ...

  7. ASP.NET MVC 过滤器开发与使用

    ASP.NET MVC 中给我们提供了内置的过滤器,通过过滤器,我们可以在控制器内的方法前后,添加必须的业务逻辑,如权限验证,身份验证,错误处理等. 今天,我们主要介绍3个过滤器:OutputCach ...

  8. java集合 collection-list-ArrayList 将自定义对象作为元素存到ArrayList集合中,并去除重复元素。

    import java.util.*; /* 将自定义对象作为元素存到ArrayList集合中,并去除重复元素. 比如:存人对象.同姓名同年龄,视为同一个人.为重复元素. 思路: 1,对人描述,将数据 ...

  9. 5中方式实现String反转

    这里介绍Java中5中实现String反转的方式. 一.数组实现String反转 //数组实现String反转 public String reverseByArray(){ if(str == nu ...

  10. 使用MySQL数据库将汉字转换成拼音的一个C语言小程序

    环境: mysql:mysql-5.1.65 centos:centos 6.5 编译命令: gcc -o chinesetopinyin chinesetopinyin.c -L/usr/lib/m ...