#include <iostream>
#include <unordered_map>
#include <functional>
// 抽象产品类
class Shape {
public:
virtual void draw() = 0;
virtual ~Shape() {}
};
// 具体产品类 - Circle
class Circle : public Shape {
public:
void draw() override {
std::cout << "Drawing Circle" << std::endl;
}
};
// 具体产品类 - Rectangle
class Rectangle : public Shape {
public:
void draw() override {
std::cout << "Drawing Rectangle" << std::endl;
}
};
// 工厂类
class ShapeFactory {
private:
// 函数指针类型定义
using CreateFunc = std::function<Shape*()>;
// 使用函数指针映射具体产品类的创建函数
std::unordered_map<std::string, CreateFunc> shapeCreators;
public:
// 注册具体产品类的创建函数
void registerShape(const std::string& type, CreateFunc createFunc) {
shapeCreators[type] = createFunc;
}
// 创建具体产品对象的方法
Shape* createShape(const std::string& type) {
auto it = shapeCreators.find(type);
if (it != shapeCreators.end()) {
return it->second();
} else {
return nullptr; // 或者抛出异常
}
}
};
int main() {
ShapeFactory factory;
// 注册具体产品类的创建函数
factory.registerShape("Circle", []() { return new Circle(); });
factory.registerShape("Rectangle", []() { return new Rectangle(); });
// 通过传参决定具体对象的类型
Shape* shape1 = factory.createShape("Circle");
Shape* shape2 = factory.createShape("Rectangle");
// 使用对象
shape1->draw(); // Drawing Circle
shape2->draw(); // Drawing Rectangle
// 释放内存
delete shape1;
delete shape2;
return 0;
}
注册回调的工厂模式[c++]
最新推荐文章于 2024-10-17 15:47:06 发布