I have to say I always try to keep code simple and beautiful, mainly using design patterns when possible. Also, I am impressed I did not find anything related to this on the internet (except simple and very vague examples, mostly in javascript using json).
The scenario is: I have to parse/build concrete objects from a file, whose content may be XML, JSON and/or other formats. Heres an example:
Concrete object:
// Contains the common states for the entities
struct EntityModel
{
int hp;
int level;
int armor;
int speed;
// Other attributes...
};
class Entity
{
// Stuff (protected/public/private attributes and functions/methods)
private:
EntityModel* m_model; // Pointer to the model used (flyweight)
// Other attributes...
}
File (XML, in this case):
<entity name="Skeleton" class="Undead">
<attributes>
<hp value="150" />
<level value="10" />
<armor value="75" />
<speed value="15" />
<width value="32" />
<height value="32" />
<experience value="372" />
<texture value="skeleton.png" />
<intelligence value="skeleton.script" />
</attributes>
<restistances>
<resist type="Shock" value="30" />
<resist type="Fire" value="10" />
</resistances>
<attacks>
<spell name="Blizzard" mp="50" damage="130" distance="0" />
<spell name="Fireball" mp="30" damage="100" distance="0" />
</attacks>
<loot>
<drop item="Gold Coin" min="30" max="50" probability="1" />
<drop item="Ruby" min="0" max="2" probability="0.7" />
<drop item="Enchanted Sword" probability="0.25" />
</loot>
</entity>
This is the example of the relationship between an entity model and its file. There will also be other objects that have to be able to be parsed/built/created from their files.
Some may say that a design pattern is not really necessary in this case, as I have seen in a few implementations, although I do really believe there is one. The whole entity creation system involves the abstract factory, pool and flyweight patterns (a createEntity call is requested to the factory, which will see if a flyweight model has already been created and cached in the pool or create and cache the new model).
So, the question is: Are there any proper way to do that? Which one?
I'll be basing on the answer for this very case and adapt to the other object creations, as I have stated. In other words, I need a generic answer.
If this post is missing some information, or is in a wrong section, please forgive me as this is my first post here.
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire