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

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

cpp 复制代码
#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 singletons
    Singleton1& singleton1 = Singleton1::getInstance();
    Singleton2& singleton2 = Singleton2::getInstance();
    Singleton3& singleton3 = Singleton3::getInstance();
    Singleton4& singleton4 = Singleton4::getInstance();

    // Verify that they are all the same instance
    if (&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 来创建对应的单例对象。

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

相关推荐
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
willow2 天前
Axios由浅入深
设计模式·axios
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
七月丶4 天前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞4 天前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼4 天前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟5 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder5 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++