c++ - 工厂方法反if实现

标签 c++ factory-method

我正在我的 C++ 项目中应用工厂设计模式,您可以在下面看到我是如何做的。我尝试通过遵循“反 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;
}

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

最佳答案

你是对的,你应该使用从键到创建函数的映射。 在你的情况下是

typedef Chip* tCreationFunc();
std::map<std::string, tCreationFunc*> microcontrollers;

为每个新的芯片驱动类 ChipXXX 添加一个静态函数:

static Chip* CreateInstance()
{
    return new ChipXXX();
}

并将此函数注册到 map 中。

你的工厂函数应该是这样的:

Chip* ChipFactory::createChip(std::string& type)
{
    ChipList::iterator existing = microcontrollers.find(type);    
    if (existing != microcontrollers.end())
        return existing->second();

    return NULL;
}

请注意,在您的示例中,不需要复制构造函数。

关于c++ - 工厂方法反if实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3501890/

相关文章:

c++ - 为什么 lambda 返回 bool 值?

design-patterns - 抽象工厂、工厂方法、生成器

java - 在 valueOf() 和 newInstance() 之间进行选择的标准是什么?

c++ - <功能> : plus<long>() on integers gives unexpected result

c++ - 使用 QVariant Maps 在 Qt 5.7 中使用更简单的方法替换 json 格式的字段

c++ - 如何使用显式强制转换来抑制此警告?

c++ - 为什么当左侧操作数为负值时,左移操作会调用未定义行为?

javascript - 有哪些使用 JavaScript 实现设计模式的示例?

javascript - 在 Javascript 中创建大量工厂对象的有效方法

c++ - 我可以在不使用 new 的情况下在 C++ 中实现工厂方法模式吗?