我正在我的 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/