【发布时间】:2010-08-17 11:29:17
【问题描述】:
我在我的 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 的情况下创建我的对象。 (我知道我有点偏执,但我想知道它是否可以做到。)
【问题讨论】:
-
至少 GOF 没有工厂模式。有工厂方法或抽象工厂。这对我来说似乎是一种工厂方法。
-
@chubsdad 他在标题中写了
Factory Method。 -
哦,我没仔细注意,谢谢
标签: c++ factory-method