在下面的示例中,我将演示如何创建一个工厂类,该工厂类能够生成四个不同类型的单例对象,每个单例对象都通过单独的工厂方法进行创建。
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
,它实现了单例模式的基本机制,然后创建了四个派生类 Singleton1
、Singleton2
、Singleton3
和 Singleton4
,每个派生类都有自己的工厂方法 getInstance
来创建对应的单例对象。
通过这种方式,每个派生类继承了单例的行为,但每个单例对象都是独立的实例。当我们调用工厂方法来获取这些单例对象时,它们确保只有一个实例存在,而且每个工厂方法创建的实例是不同的,即每个单例类都有自己的单例实例。