工厂方法反IF实现 [英] Factory method anti-if implementation
问题描述
我正在C ++项目中应用Factory设计模式,下面您可以看到我的工作方式.我尝试通过遵循"anti-if"活动来改进代码,因此想删除我拥有的if语句.知道我该怎么办吗?
I'm applying the Factory design pattern in my C++ project, and below you can see how I am doing it. I try to improve my code by following the "anti-if" campaign, thus want to remove the if statements that I am having. Any idea how can I do it?
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的情况下创建我的对象. (我知道我有点偏执,但是我想知道是否可以做到.)
I would imagine creating a map, with string as the key, and the constructor (or something to create the object). After that, I can just get the constructor from the map using the type (type are strings) and create my object without any if. (I know I'm being a bit paranoid, but I want to know if it can be done or not.)
推荐答案
是的,您应该使用从键到创建函数的映射. 在您的情况下,将是
You are right, you should use a map from key to creation-function. In your case it would be
typedef Chip* tCreationFunc();
std::map<std::string, tCreationFunc*> microcontrollers;
为每个新的芯片驱动类ChipXXX添加一个静态函数:
for each new chip-drived class ChipXXX add a static function:
static Chip* CreateInstance()
{
return new ChipXXX();
}
并将此功能注册到地图中.
and also register this function into the map.
您的工厂功能应该是这样的:
Your factory function should be somethink like this:
Chip* ChipFactory::createChip(std::string& type)
{
ChipList::iterator existing = microcontrollers.find(type);
if (existing != microcontrollers.end())
return existing->second();
return NULL;
}
请注意,就像您的示例一样,不需要复制构造函数.
Note that copy constructor is not needed, as in your example.
这篇关于工厂方法反IF实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!