当前位置: 首页 > news >正文

Singleton(单例模式)

1. 意图

        在开发中,若某些模块或功能只需要一个类实例,所有调用地方通过着一个类对象访问功能,单例模式符合这种类实例创建模式,并且通过提供统一类实例接口访问类对象。

2. 适用性

        《Gof 设计模式-可复用面向对象软件的基础》中对此模式的适用性描述如下:

  • 当类只能有一个实例且客户可以从一个公众的访问点访问。
  •  当这个唯一实例应该是通过子类化可拓展的,并且客户应该无需更改代码就能使用一个扩展的实例时。

3. 实现

  • 饿汉模式:类加载时,类对象创建并初始化,调用时直接使用已经创建好的。
#include <iostream>class Singleton {
public:static Singleton *GetInstance() { return m_instance; }void Print() { std::cout << __FUNCTION__ << std::endl; }private:Singleton() = default;~Singleton() = default;Singleton(const Singleton &) = delete;Singleton &operator=(const Singleton &) = delete;private:static Singleton *m_instance;
};Singleton *Singleton::m_instance = new Singleton;void Test() { Singleton::GetInstance()->Print(); }int main() {Test();return 0;
}
  • 懒汉模式:类对象创建与初始化被延迟到真正调用的位置。
#include <iostream>class Singleton {
public:static Singleton *GetInstance() {if (m_instance == nullptr)m_instance = new Singleton;return m_instance;}void Print() { std::cout << __FUNCTION__ << std::endl; }private:Singleton() = default;~Singleton() = default;Singleton(const Singleton &) = delete;Singleton &operator=(const Singleton &) = delete;private:static Singleton *m_instance;
};Singleton *Singleton::m_instance = nullptr;void Test() { Singleton::GetInstance()->Print(); }int main() {Test();return 0;
}

        懒汉模式存在多线程并发问题,可以加锁,如下

#include <iostream>
#include <mutex>std::mutex mtx;class Singleton {
public:static Singleton *GetInstance() {std::lock_guard<std::mutex> locker(mtx);if (m_instance == nullptr)m_instance = new Singleton;return m_instance;}void Print() { std::cout << __FUNCTION__ << std::endl; }private:Singleton() = default;~Singleton() = default;Singleton(const Singleton &) = delete;Singleton &operator=(const Singleton &) = delete;private:static Singleton *m_instance;
};

        以上通过加锁保证了数据的并发安全,但若此对象创建好后多个线程频繁调用,每次都加锁访问可读对象,对程序性能影响较大,于是又出现了双层检查机制,优化访问性能。

#include <iostream>
#include <mutex>std::mutex mtx;class Singleton {
public:static Singleton *GetInstance() {if (m_instance == nullptr) {std::lock_guard<std::mutex> locker(mtx);if (m_instance == nullptr)m_instance = new Singleton;}return m_instance;}void Print() { std::cout << __FUNCTION__ << std::endl; }private:Singleton() = default;~Singleton() = default;Singleton(const Singleton &) = delete;Singleton &operator=(const Singleton &) = delete;private:static Singleton *m_instance;
};Singleton *Singleton::m_instance = nullptr;void Test() { Singleton::GetInstance()->Print(); }int main() {Test();return 0;
}

        双重检查机制实际上还存在潜在的问题,内存访问重新排序(重新排列编译器产生的汇编指令)导致双重锁定失效(考虑类对象内存分配和调用构造函数初始化分为两步执行,指令不顺序执行就无法保证多线程有其它指令在这两步之间执行)。所以需要保证指令顺序执行,避免指令重排。

#include <atomic>
#include <iostream>
#include <mutex>class Singleton {
public:static Singleton *GetInstance() {Singleton *tmp = m_instance.load(std::memory_order_relaxed);std::atomic_thread_fence(std::memory_order_acquire);if (tmp == nullptr) {std::lock_guard<std::mutex> locker(m_mtx);tmp = m_instance.load(std::memory_order_relaxed);if (tmp == nullptr) {tmp = new Singleton;std::atomic_thread_fence(std::memory_order_release);m_instance.store(tmp, std::memory_order_relaxed);}}return m_instance;}void Print() { std::cout << __FUNCTION__ << std::endl; }private:Singleton() = default;~Singleton() = default;Singleton(const Singleton &) = delete;Singleton &operator=(const Singleton &) = delete;private:static std::atomic<Singleton *> m_instance;static std::mutex m_mtx;
};std::atomic<Singleton *> Singleton::m_instance = nullptr;
std::mutex Singleton::m_mtx;void Test() { Singleton::GetInstance()->Print(); }int main() {Test();return 0;
}

        以上使用原子变量及内存序约束实现单例类,避免指令重排问题,同时解决并发问题。但实现略微繁琐,c++11以后对静态变量创建的并发安全提供了保证,简化写法如下:

#include <iostream>class Singleton {
public:static Singleton &GetInstance() {static Singleton instance;return instance;}void Print() { std::cout << __FUNCTION__ << std::endl; }private:Singleton() = default;~Singleton() = default;Singleton(const Singleton &) = delete;Singleton &operator=(const Singleton &) = delete;
};void Test() { Singleton::GetInstance().Print(); }int main() {Test();return 0;
}

4. 优缺点

  • 控制类实例数量
  • 比类操作更灵活,减少命名空间污染
  • 隐藏了类之间的依赖关系
  • 影响代码的扩展性
  • 影响代码的可测试性
  • 不支持包含参数的构造函数

5. 模板实现

  • 单实例管理
template <typename T> class SingletonManager {
public:template <typename... Args> static T &GetInstance(Args &&...args) {static T instance(std::forward<Args>(args)...);return instance;}private:SingletonManager() = default;virtual ~SingletonManager() = default;SingletonManager(const SingletonManager &) = delete;SingletonManager &operator=(const SingletonManager &) = delete;
};
  • 多实例管理
#include <map>
#include <memory>
#include <string>template <typename T, typename K = std::string> class MultitonManager {
public:template <typename... Args>static T &GetInstance(const K &key, Args &&...args) {return AssignInstance(key, std::forward<Args>(args)...);}template <typename... Args> static T &GetInstance(K &&key, Args &&...args) {return AssignInstance(key, std::forward<Args>(args)...);}private:template <typename Key, typename... Args>static T &AssignInstance(Key &&key, Args &&...args) {auto iter = m_map.find(key);if (iter == m_map.end()) {static T instance;m_map.emplace(key, &instance);return instance;}return *(iter->second);}private:MultitonManager() = default;virtual ~MultitonManager() = default;MultitonManager(const MultitonManager &) = delete;MultitonManager &operator=(const MultitonManager &) = delete;private:static std::map<K, T *> m_map;
};template <typename T, typename K> std::map<K, T *> MultitonManager<T, K>::m_map;

http://www.lryc.cn/news/456015.html

相关文章:

  • 【Linux报错】“-bash: cd: too many arguments“
  • C# WebService返回参数为DataTable报错“XML文档有错误”
  • [paddle]paddleseg快速开始
  • UNIAPP popper气泡弹层【unibest框架下】vue3+typescript
  • launcher.py: error: the following arguments are required: --output_dir
  • C语言基础之结构体
  • Redis入门第四步:Redis发布与订阅
  • MySQL 之权限与授权
  • 解决方案:Pandas里面的loc跟iloc,有什么区别
  • C# 和 C++ 混合编程
  • Vxe UI vue vxe-table 实现表格单元格选中功能
  • 组合模式详解
  • AltiumDesigner脚本开发-DIP封装制作
  • 乌班图基础设施安装之Mysql8.0+Redis6.X安装
  • 【动态规划-最长递增子序列(LIS)】力扣673.最长递增子序列的个数
  • SQL优化 where谓词条件is null优化
  • Starrocks 元数据恢复 failed to load journal type 10242
  • 《深度学习》神经语言模型 Word2vec CBOW项目解析、npy/npz文件解析
  • 黄粱一梦,镜花水月总是空
  • 【分布式事务-01】分布式事务之2pc两阶段提交
  • docker 安装 rabbitMQ
  • 知识改变命运 数据结构【java对象的比较】
  • 01_23 种设计模式之《简单工厂模式》
  • Android 12.0 关于定制自适应AdaptiveIconDrawable类型的动态日历图标的功能实现系列一
  • 【源码+文档+调试讲解】基于安卓的小餐桌管理系统springboot框架
  • C语言中的文件操作(二)
  • 【C++篇】继承之韵:解构编程奥义,领略面向对象的至高法则
  • Ubuntu 22.04 安装 KVM
  • 101 公司战略的基本概念
  • 【devops】devops-ansible之剧本初出茅庐--搭建rsync和nfs