注册回调的工厂模式[c++]

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值