phu*_*ehe 1 c++ factory-method
我正在我的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.(我知道我有点偏执,但我想知道它是否可以完成.)
你是对的,你应该使用从键到创建功能的映射.在你的情况下,它会
typedef Chip* tCreationFunc();
std::map<std::string, tCreationFunc*> microcontrollers;
Run Code Online (Sandbox Code Playgroud)
为每个新的芯片驱动类ChipXXX添加一个静态功能:
static Chip* CreateInstance()
{
return new ChipXXX();
}
Run Code Online (Sandbox Code Playgroud)
并将此功能注册到地图中.
你的工厂功能应该是这样的一些想法:
Chip* ChipFactory::createChip(std::string& type)
{
ChipList::iterator existing = microcontrollers.find(type);
if (existing != microcontrollers.end())
return existing->second();
return NULL;
}
Run Code Online (Sandbox Code Playgroud)
请注意,不需要复制构造函数,如示例中所示.