C++实现设计模式之 —— 单例模式 Singleton
2015-07-07 20:40
696 查看
单例模式是最简单的创建型模式,当某个类只需要唯一的一份实例时,使用单例模式可以确保不会创建多余的实例。在C++ 中,单例模式可以避免全局变量的使用。下面是一个典型的线程安全的单例模式
为了确保线程安全,我们需要对创建实例部分进行线程加锁,上述示例代码使用了双重检查的方式,既能够确保线程安全,也避免了由于每次加锁导致的性能消耗。如果使用下面的实现方式:
则每次调用GetInstance() 都需要加锁。
#ifndef Singleton_h__ #define Singleton_h__ #include <mutex> //C++11 class CSingleton { public: static CSingleton* GetInstance() { if (m_pInstance == NULL) { m_lock.lock(); //double check for better performance if (m_pInstance == NULL) { m_pInstance = new CSingleton(); } m_lock.unlock(); } return m_pInstance; } static void Destroy() { m_lock.lock(); delete m_pInstance; m_pInstance = NULL; m_lock.unlock(); } void Method() { // } private: CSingleton(){} ~CSingleton() { delete m_pInstance; m_pInstance = NULL; } //Disable copy and assign CSingleton(const CSingleton& rhs); CSingleton& operator = (const CSingleton& rhs); private: static CSingleton* m_pInstance; static std::mutex m_lock; }; CSingleton* CSingleton::m_pInstance = NULL; std::mutex CSingleton::m_lock; #endif // Singleton_h__
为了确保线程安全,我们需要对创建实例部分进行线程加锁,上述示例代码使用了双重检查的方式,既能够确保线程安全,也避免了由于每次加锁导致的性能消耗。如果使用下面的实现方式:
static CSingleton* GetInstance() { m_lock.lock(); if (m_pInstance == NULL) { m_pInstance = new CSingleton(); } m_lock.unlock(); return m_pInstance; }
则每次调用GetInstance() 都需要加锁。
相关文章推荐
- 黑马-C语言-函数,变量,及变量作用范围
- c++ primer--容器的综合应用:文本查询程序
- c++ STL stack & queue
- C/C++中的日期和时间 time_t与struct tm变换
- 初学C语言之结构体
- c++友元函数和友元类
- hello, world
- 黑马程序员-C语言学习笔记(一)
- c++ primer读书笔记-第十章 关联容器
- gcc编译C++程序
- c语言编程中字节对齐的问题
- 兔子c++
- C语言中声明与定义的区别
- 函数的返回值是函数指针的指针函数
- C语言打印华氏-摄氏温度对照表的方法
- C语言实现封装、继承和多态
- 如何成为游戏的生产者——第二章:如何开始你的编程(开发环境的搭建、C++语言适应)
- C++ exit 与 return 浅析
- C语言实现顺序栈的基本操作(初始化、判断空、入栈、出栈、获取栈顶元素)
- C++实现一个简单图书借阅流程