我正在考虑使用工厂函数在同一层次结构中创建不同的类。我了解通常工厂通常执行如下:
Person* Person::Create(string type, ...)
{
// Student, Secretary and Professor are all derived classes of Person
if ( type == "student" ) return new Student(...);
if ( type == "secretary" ) return new Secretary(...);
if ( type == "professor" ) return new Professor(...);
return NULL;
}
我正在尝试一种方法,使该过程可以自动化,从而不需要对各种条件进行硬编码。
到目前为止,我能想到的唯一方法是使用地图和原型模式:
该映射将在第一个元素中保存类型字符串,在第二个元素中保存类实例(原型):
std::map<string, Person> PersonClassMap;
// This may be do-able from a configuration file, I am not sure
PersonClassMap.insert(make_pair("student", Student(...)));
PersonClassMap.insert(make_pair("secondary", Secretary(...)));
PersonClassMap.insert(make_pair("professor", Professor(...)));
该函数可能如下所示:
Person* Person::Create(string type)
{
map<string, Person>::iterator it = PersonClassMap.find(type) ;
if( it != PersonClassMap.end() )
{
return new Person(it->second); // Use copy constructor to create a new class instance from the prototype.
}
}
不幸的是,原型方法仅在您只希望工厂创建的类每次都相同时才有效,因为它不支持参数。
有谁知道是否有可能以一种好的方式做到这一点,还是我坚持使用工厂功能?