I am considering a factory function to create different classes in the same hierarchy. I understand that normally a factory is normally implemented as follows:
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;
}
I am trying to think of a way so that the process can be automated so that the various conditions do not need to be hard-coded.
So far the only way I can think of is using a map and the prototype pattern:
The map will hold the type string in the first element and a class instance (prototype) in the second:
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(...)));
The function may look something like this:
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.
}
}
Unfortunately, the prototype method only works if you only want the class created by the factory to be identical every time, since it does not support arguments.
Does anybody know if it is possible to do it in a nice way, or am I stuck with the factory function?