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

C++ 的设计模式之 工厂方法加单例

在下面的示例中,我将演示如何创建一个工厂类,该工厂类能够生成四个不同类型的单例对象,每个单例对象都通过单独的工厂方法进行创建。

#include <iostream>
#include <mutex>// Singleton base class
class Singleton {
protected:Singleton() {}public:Singleton(const Singleton&) = delete;Singleton& operator=(const Singleton&) = delete;static Singleton& getInstance() {static Singleton instance;return instance;}void doSomething() {std::cout << "Singleton is doing something." << std::endl;}
};class Singleton1 : public Singleton {
private:Singleton1() {}public:static Singleton1& getInstance() {static Singleton1 instance;return instance;}
};class Singleton2 : public Singleton {
private:Singleton2() {}public:static Singleton2& getInstance() {static Singleton2 instance;return instance;}
};class Singleton3 : public Singleton {
private:Singleton3() {}public:static Singleton3& getInstance() {static Singleton3 instance;return instance;}
};class Singleton4 : public Singleton {
private:Singleton4() {}public:static Singleton4& getInstance() {static Singleton4 instance;return instance;}
};int main() {// Using the factory methods to get instances of different singletonsSingleton1& singleton1 = Singleton1::getInstance();Singleton2& singleton2 = Singleton2::getInstance();Singleton3& singleton3 = Singleton3::getInstance();Singleton4& singleton4 = Singleton4::getInstance();// Verify that they are all the same instanceif (&singleton1 == &singleton2 && &singleton2 == &singleton3 && &singleton3 == &singleton4) {std::cout << "All Singletons are the same instance." << std::endl;}singleton1.doSomething();singleton2.doSomething();singleton3.doSomething();singleton4.doSomething();return 0;
}

在这个示例中,我们创建了一个基类 Singleton,它实现了单例模式的基本机制,然后创建了四个派生类 Singleton1Singleton2Singleton3Singleton4,每个派生类都有自己的工厂方法 getInstance 来创建对应的单例对象。

通过这种方式,每个派生类继承了单例的行为,但每个单例对象都是独立的实例。当我们调用工厂方法来获取这些单例对象时,它们确保只有一个实例存在,而且每个工厂方法创建的实例是不同的,即每个单例类都有自己的单例实例。

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

相关文章:

  • Deploy、Service与Ingress
  • 定制化推送+精细化运营,Mobpush助力《迷你世界》用户留存率提升23%
  • 深度学习零基础教程
  • 简单测试一下 展锐的 UDX710 性能
  • 一百九十、Hive——Hive刷新分区MSCK REPAIR TABLE
  • 智慧公厕:探索未来城市环境卫生设施建设新标杆
  • 高压放大器在无线电能中应用有哪些
  • 若依集成MybatisPlus
  • List小练习,实现添加图书,并且有序遍历
  • 代码随想录二刷 Day42
  • 【Android】Drawable 和src 的区别和理解
  • Linux网络-UDP/TCP协议详解
  • C语言从入门到高级
  • 【MultiOTP】在Linux上使用MultiOTP进行SSH登录
  • 性能超越 Clickhouse | 物联网场景中的毫秒级查询案例
  • 05、SpringBoot 集成 RocketMQ
  • PR2023中如何导入字幕
  • 读书笔记--华为数据之道有感
  • 汽车数据安全事件频发,用户如何保护隐私信息?
  • Redis主从复制流程
  • 微信公众号如何变更为订阅号?
  • 竞赛选题 深度学习YOLO抽烟行为检测 - python opencv
  • mysql利用mysqldump方式搭建主从
  • 如何保护IP在线隐私,提高网络安全?
  • 掌握 C++ 编译过程:面试中常见问题解析
  • 了解Qt QScreen的geometry ,size
  • 云安全—云计算基础
  • 【ARM Coresight Debug 系列 16 -- Linux 断点 BRK 中断使用详细介绍】
  • Rust星号(*)的作用-基础篇
  • 企业该如何选择数字化转型工具?