I am working on a game and trying to implement a smart way to create npc objects in C ++ when parsing a text file.
This is currently hardcoded in the Factory object. Like this:
IActor * ActorFactory::create(string actortype, Room * r, string name, int hp) { if(actortype == "Troll") { return new Troll(r, name, hp); } if (actortype == "Dragon") { return new Dragon(r, name, hp); }
This, in my opinion, is a very ugly way to do this. Since it (by the way) breaks the principle of Open / Closed .
I participate in Java, and in Java I would do something like each IActor reporting this class name and class type ActorFactory at the beginning of program execution. Then the factory will save the relation on the map and then can easily find which lines the object displays, and then it can easily instantiate it.
Edit: I would also like to be able to call a constructor with a variable number / type of arguments.
How to do it in C ++? Can this be done?
c ++ factory
Martin nycander
source share