c++的单例模式及c++11对单例模式的优化
单例模式
单例模式,可以说设计模式中最常应用的一种模式了,据说也是面试官最喜欢的题目。但是如果没有学过设计模式的人,可能不会想到要去应用单例模式,面对单例模式适用的情况,可能会优先考虑使用全局或者静态变量的方式,这样比较简单,也是没学过设计模式的人所能想到的最简单的方式了。
一般情况下,我们建立的一些类是属于工具性质的,基本不用存储太多的跟自身有关的数据,在这种情况下,每次都去new一个对象,即增加了开销,也使得代码更加臃肿。其实,我们只需要一个实例对象就可以。如果采用全局或者静态变量的方式,会影响封装性,难以保证别的代码不会对全局变量造成影响。
考虑到这些需要,我们将默认的构造函数声明为私有的,这样就不会被外部所new了,甚至可以将析构函数也声明为私有的,这样就只有自己能够删除自己了。在Java和C#这样纯的面向对象的语言中,单例模式非常好实现,直接就可以在静态区初始化instance,然后通过getInstance返回,这种就被称为饿汉式单例类。也有些写法是在getInstance中new instance然后返回,这种就被称为懒汉式单例类,但这涉及到第一次getInstance的一个判断问题。
下面的代码只是表示一下,跟具体哪种语言没有关系。
单线程中:
Singleton* getInstance()
{
if (instance == NULL)
instance = new Singleton(); return instance;
}
这样就可以了,保证只取得了一个实例。但是在多线程的环境下却不行了,因为很可能两个线程同时运行到if (instance == NULL)这一句,导致可能会产生两个实例。于是就要在代码中加锁。
Singleton* getInstance()
{
lock();
if (instance == NULL)
{
instance = new Singleton();
}
unlock(); return instance;
}
但这样写的话,会稍稍映像性能,因为每次判断是否为空都需要被锁定,如果有很多线程的话,就爱会造成大量线程的阻塞。于是出现了双重锁定。
Singleton* getInstance()
{
if (instance == NULL)
{
lock();
if (instance == NULL)
{
instance = new Singleton();
}
unlock();
} return instance;
}
这样只够极低的几率下,通过越过了if (instance == NULL)的线程才会有进入锁定临界区的可能性,这种几率还是比较低的,不会阻塞太多的线程,但为了防止一个线程进入临界区创建实例,另外的线程也进去临界区创建实例,又加上了一道防御if (instance == NULL),这样就确保不会重复创建了。
常用的场景
单例模式常常与工厂模式结合使用,因为工厂只需要创建产品实例就可以了,在多线程的环境下也不会造成任何的冲突,因此只需要一个工厂实例就可以了。
优点
1.减少了时间和空间的开销(new实例的开销)。
2.提高了封装性,使得外部不易改动实例。
缺点
1.懒汉式是以时间换空间的方式。(上面使用的方式)
2.饿汉式是以空间换时间的方式。(下面使用的方式)
#ifndef _SINGLETON_H_
#define _SINGLETON_H_ class Singleton{
public:
static Singleton* getInstance(); private:
Singleton();
//把复制构造函数和=操作符也设为私有,防止被复制
Singleton(const Singleton&);
Singleton& operator=(const Singleton&); static Singleton* instance;
}; #endif #include "Singleton.h" Singleton::Singleton(){ } Singleton::Singleton(const Singleton&){ } Singleton& Singleton::operator=(const Singleton&){ } //在此处初始化
Singleton* Singleton::instance = new Singleton();
Singleton* Singleton::getInstance(){
return instance;
} #include "Singleton.h"
#include <stdio.h> int main(){
Singleton* singleton1 = Singleton::getInstance();
Singleton* singleton2 = Singleton::getInstance(); if (singleton1 == singleton2)
fprintf(stderr,"singleton1 = singleton2\n"); return ;
}
以上使用的方式存在问题:只能实例化没有参数的类型,其它带参数的类型就不行了。
c++11 为我们提供了解决方案:可变模板参数
template <typename T>
class Singleton
{
public:
template<typename... Args>
static T* Instance(Args&&... args)
{
if(m_pInstance==nullptr)
m_pInstance = new T(std::forward<Args>(args)...);
return m_pInstance;
}
static T* GetInstance()
{
if (m_pInstance == nullptr)
throw std::logic_error("the instance is not init, please initialize the instance first");
return m_pInstance;
}
static void DestroyInstance()
{
delete m_pInstance;
m_pInstance = nullptr;
} private:
Singleton(void);
virtual ~Singleton(void);
Singleton(const Singleton&);
Singleton& operator = (const Singleton&);
private:
static T* m_pInstance;
}; template <class T> T* Singleton<T>::m_pInstance = nullptr;
由于原来的接口中,单例对象的初始化和取值都是一个接口,可能会遭到误用,更新之后,讲初始化和取值分为两个接口,单例的用法为:先初始化,后面取值,如果中途销毁单例的话,需要重新取值。如果没有初始化就取值则会抛出一个异常。
Multiton的实现
#include <map>
#include <string>
#include <memory>
using namespace std; template < typename T, typename K = string>
class Multiton
{
public:
template<typename... Args>
static std::shared_ptr<T> Instance(const K& key, Args&&... args)
{
return GetInstance(key, std::forward<Args>(args)...);
} template<typename... Args>
static std::shared_ptr<T> Instance(K&& key, Args&&... args)
{
return GetInstance(key, std::forward<Args>(args)...);
}
private:
template<typename Key, typename... Args>
static std::shared_ptr<T> GetInstance(Key&& key, Args&&...args)
{
std::shared_ptr<T> instance = nullptr;
auto it = m_map.find(key);
if (it == m_map.end())
{
instance = std::make_shared<T>(std::forward<Args>(args)...);
m_map.emplace(key, instance);
}
else
{
instance = it->second;
} return instance;
} private:
Multiton(void);
virtual ~Multiton(void);
Multiton(const Multiton&);
Multiton& operator = (const Multiton&);
private:
static map<K, std::shared_ptr<T>> m_map;
}; template <typename T, typename K>
map<K, std::shared_ptr<T>> Multiton<T, K>::m_map;
c++的单例模式及c++11对单例模式的优化的更多相关文章
- c++11 实现单例模式
C++11出来后,里面新增加了好多好用的功能 下面的单例就是使用了C++11中的标准库中的mutex和unique_prt 进行内存管理的. 此单例模式不用担心内存的释放问题 #pragma once ...
- DCL单例模式中的缺陷及单例模式的其他实现
DCL:Double Check Lock ,意为双重检查锁.在单例模式中懒汉式中可以使用DCL来保证程序执行的效率. 1 public class SingletonDemo { 2 private ...
- java单例模式教程之java实现单例模式的8大方法
单例模式是Java中常用的设计模式之一.单例模式属于创建型模式,它提供了一种创建对象的最佳方式. 单例模式只创建类的一个对象,之后在一定范围为可任意调用,确保只有单个对象被创建.这个类提供了一种访问其 ...
- Python中的单例模式的几种实现方式和优化以及pyc文件解释(转)
原文:https://www.cnblogs.com/huchong/p/8244279.html 另一篇关于.pyc文件是什么? 原文: http://blog.sina.com.cn//s/bl ...
- VMware 11安装Mac OS X 10.11.5虚拟机以及优化心得
随着苹果WWC大会退出了MAC最新版的10.11.5,本着一颗“极客”的心情,在第一时间用VMWARE虚拟机装上了.然后各种卡顿这里分享一下优化mac虚拟机的心得. 1 从Dock上移除Dashboa ...
- Java虚拟机11:运行期优化
前言 http://www.cnblogs.com/xrq730/p/4839245.html,HotSpot采用的是解释器+编译器并存的架构,之前的这篇文章里面已经讲过了,本文只是把即时编译器这块再 ...
- 【jQuery基础学习】11 jQuery性能简单优化
关于性能优化 合适的选择器 $("#id")会直接调用底层方法,所以这是最快的.如果这样不能直接找到,也可以用find方法继续查找 $("p")标签选择器也是直 ...
- 11 MySQL之性能优化
01-优化简介 MySQL数据库优化是多方面的,原则是减少系统瓶颈,减少资源的占用,增加系统的反应速度. 1.通过优化文件系统,提高磁盘I\O的速写速度: 2.通过优化操作系统的调度策略,提高MySQ ...
- GJM : C#设计模式(1)——单例模式
感谢您的阅读.喜欢的.有用的就请大哥大嫂们高抬贵手"推荐一下"吧!你的精神支持是博主强大的写作动力以及转载收藏动力.欢迎转载! 版权声明:本文原创发表于 [请点击连接前往] ,未经 ...
随机推荐
- 1001 字符串“水”题(二进制,map,哈希)
1001: 字符串“水”题 时间限制: 1 Sec 内存限制: 128 MB提交: 210 解决: 39[提交][状态][讨论版] 题目描述 给出一个长度为 n 的字符串(1<=n<= ...
- Android开发中dp、dpi、px的区别(转)
一.基本概念 - dp:安卓中的相对大小 - dpi:(dot per inch)每英寸像素多少 - px:像素点 二.详细说明 1.px和dpi - px: 平常所说的1920×1080只是像素数量 ...
- NSObject头文件解析 / 消息机制 / Runtime解读 (二)
本章接着NSObject头文件解析 / 消息机制 / Runtime解读(一)写 给类添加属性: BOOL class_addProperty(Class cls, const char *name, ...
- python_查找模块的方法
在python自带的Command Line中: 1. 查找一个模块拥有的方法 import 模块名 help(模块名) or dir(模块名) 2. 查找一个模块拥有的方法 import 模块名 h ...
- queue容器
一.queue特性 queue是一种先进先出(first in first out,FIFO)的数据结构,它有两个口,数据元素只能从一个口进,从另一个口出.队列只允许从队尾加入元素,队头删除元素,必须 ...
- SpringCloud基础教程学习记录
这个学习记录是学习自翟永超前辈的SpringCloud的基础教程. 自己写这个教程的目的主要是在于,想要更凝练总结一些其中的一些实用点,顺便做个汇总,这样自己在复习查看的时候更加方便,也能顺着自己的思 ...
- 第11篇 PSR-0 规范
Mandatory A fully-qualified namespace and class must have the following structure \<Vendor Name&g ...
- ZOJ 4016 Mergeable Stack(栈的数组实现)
Mergeable Stack Time Limit: 2 Seconds Memory Limit: 65536 KB Given initially empty stacks, the ...
- Rails、Nginx、Passenger、bundle之间的协作关系
引自:http://www.zhihu.com/question/20062163 Bundle是Gem包的依赖管理工具,RubyGem本身有依赖管理为何还要Bundle呢?有时候两个gem虽然都依赖 ...
- mysql查询最近30天、7天、每天、昨天、上个月的记录
一些变量说明: add_time为插入的时间 to_days是sql函数,返回的是个天数 data_sub(date,INTERVAL expr type)给指定的日期减去多少天 data()函数 ...