I have an XML that describes animals, each animal has different parameters, looks something like this:
<Animals>
<Cat>
</fur>
</taillength>
</Cat>
<Elephant>
</earsize>
</Elephant>
</Animals>
And I have classes (Cat, Elephant) that Inherit from :
IAnimal
{
public: virtual IAnimal* CreateAnimal(xml) = 0 ;
}
So each class can create itself, which is great.
The problem is, that somewhere (In some factory) I must have the following code:
string name = xml->getname();
if(name.equals("cat")
{
cat.CreateAnimal(xml);
} else if (name.equals("elephant"))
{
elephant.CreateAnimal(xml);
}
I want to avoid that code by creating a map from String (cat/elephant) to Class that parses this types (Cat : IAnimal, Elephant : IAnimal)
And then doing the following:
map<string, IAnimal>
// populate map ...
// ...
string name = xml->getname();
mymap[name]->CreateAnimal(xml);
The problem is to populate the map automatically, so each class will add itself at run time automatically to the map (something that can be done using static constructor in C#).
I would be happy to hear suggestions to how to do it, Thanks