(2) 简单工厂
简单工厂是创建型设计模式的核心之一,它通过一个工厂类来封装对象的创建过程,使得客户端代码无需关心具体类的实例化细节,从而实现解耦。
工厂模式有三种主要形式:
- 简单工厂 (Simple Factory)
- 工厂方法 (Factory Method)
- 抽象工厂 (Abstract Factory)
1. 极简模板工厂(Simple Factory with Template)
struct SimpleFactory {
// 使用可变参数模板创建任意类型对象
template <typename T, typename... Args>
static std::unique_ptr<T> create(Args&&... args) {
return std::make_unique<T>(std::forward<Args>(args)...);
}
// 如果你想不用智能指针,也可以返回值:
template <typename T, typename... Args>
static T create(Args&&... args) {
return T(std::forward<Args>(args)...); // 直接返回对象(值语义)
}
};
----------------------------------------------------------------
// 创建无参对象
auto dog = SimpleFactory::create<Dog>();
// 创建带一个参数的对象
auto cat = SimpleFactory::create<Cat>("小白");
注册式简单工厂
使用枚举(ProductType)作为创建对象的输入
使用模板自动关联枚举与具体类型
工厂统一创建,返回基类指针
简单、易用、可扩展
// 产品枚举
enum class ProductType {
TYPE_A,
TYPE_B
};
// 产品基类
class Product {
public:
virtual ~Product() = default;
virtual void show() const = 0;
};
// 具体产品
class ProductA : public Product {
public:
void show() const override {
std::cout << "Product A\n";
}
};
class ProductB : public Product {
public:
void show() const override {
std::cout << "Product B\n";
}
};
#include <iostream>
#include <memory>
#include <unordered_map>
#include <functional>
// 简单工厂(模板 + 枚举)
class SimpleFactory {
private:
// 函数对象类型:创建 Product 的函数
using Creator = std::function<std::unique_ptr<Product>()>;
static std::unordered_map<ProductType, Creator>& getCreatorMap() {
static std::unordered_map<ProductType, Creator> map;
return map;
}
public:
// 模板注册函数:将 枚举值 <-> 具体类型 关联
template <typename T>
static void registerType(ProductType type) {
getCreatorMap()[type] = []() {
return std::make_unique<T>();
};
}
// 运行时根据枚举创建对象
static std::unique_ptr<Product> create(ProductType type) {
auto it = getCreatorMap().find(type);
if (it != getCreatorMap().end()) {
return it->second();
}
return nullptr; // 或抛出异常
}
};
// 1. 注册类型(只需一次,通常在程序启动时)
SimpleFactory::registerType<ProductA>(ProductType::TYPE_A);
SimpleFactory::registerType<ProductB>(ProductType::TYPE_B);
// 2. 使用枚举创建对象
auto productA = SimpleFactory::create(ProductType::TYPE_A);
if (productA) {
productA->show(); // 输出: Product A
}
auto productB = SimpleFactory::create(ProductType::TYPE_B);
if (productB) {
productB->show(); // 输出: Product B
}
进阶,自动注册(使用静态变量)
// 宏:自动注册
#define REGISTER_PRODUCT(type_enum, class_name) \
namespace { \
struct AutoRegister_##class_name { \
AutoRegister_##class_name() { \
SimpleFactory::registerType<class_name>(type_enum); \
} \
}; \
static AutoRegister_##class_name reg; \
}
// 在全局作用域调用(如 .cpp 文件中)
REGISTER_PRODUCT(ProductType::TYPE_A, ProductA);
REGISTER_PRODUCT(ProductType::TYPE_B, ProductB);
浙公网安备 33010602011771号