相关疑难解决方法(0)

工厂方法反执行

我正在我的C++项目中应用Factory设计模式,下面你可以看到我是如何做到的.我尝试通过遵循"反if"活动来改进我的代码,因此想要删除我所拥有的if语句.不知道怎么办呢?

typedef std::map<std::string, Chip*> ChipList;

Chip* ChipFactory::createChip(const std::string& type) {
    MCList::iterator existing = Chips.find(type);
    if (existing != Chips.end()) {
        return (existing->second);
    }
    if (type == "R500") {
        return Chips[type] = new ChipR500();
    }
    if (type == "PIC32F42") {
        return Chips[type] = new ChipPIC32F42();
    }
    if (type == "34HC22") {
        return Chips[type] = new Chip34HC22();
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我会想象创建一个以字符串为键的映射,以及构造函数(或创建对象的东西).之后,我可以使用类型(类型是字符串)从地图中获取构造函数并创建我的对象而不使用任何if.(我知道我有点偏执,但我想知道它是否可以完成.)

c++ factory-method

1
推荐指数
2
解决办法
2702
查看次数

标签 统计

c++ ×1

factory-method ×1