1

I'm stuck at some point in my understanding of how XML deserialization could help me define my classes through XML files.

Let's say I have a new XML definition file for 2 kind of monsters, like this:

<MonstersCollection>
  <Monsters>
    <Monster>
      <MonsterName>Dragon<MonsterName>
      <HitPoints>100</Hitpoints>
    </Monster>
    <Monster>
      <MonsterName>Beast<MonsterName>
      <HitPoints>75</Hitpoints>
    </Monster>
  </Monsters>
</MonstersCollection>

Using XML deserializer, I get a nice List with my 2 differents monsters in it and everything is fine.

But how could I easily and elegantly instantiate a new Dragon Monster or Beast Monster elsewhere?

Should I have to clone the corresponding object in the List, or is there any other way to do this?

Ultimately, I would like to be able to do something as simple as:

MonsterType monsterType = MonsterType.Dragon
Monster newMonster = new Monster(monsterType)

And have the constructor automatically populate this new object properties with the Dragon data from the XML definition file.

Any help would be greatly appreciated.

John-P
  • 13
  • 2
  • This has been asked and answered here: – peterpep Nov 29 '16 at 20:18
  • If you are looking for a utility to deep-clone your `Monster` object, see [Deep cloning objects](https://stackoverflow.com/questions/78536/deep-cloning-objects/), specifically [this answer](https://stackoverflow.com/questions/78536/deep-cloning-objects/1834578#1834578) which uses `XmlSerializer`. – dbc Nov 29 '16 at 20:19
  • I went with Chintana Meegamarachchi solution but this is nonetheless very interesting, thank you for the links. – John-P Dec 02 '16 at 08:54

1 Answers1

0

One way to go is to use factory pattern. Provided you have a collection of monsters you got from your XML file, you should create a factory class which will create a monster given a monster type. This way your creation logic is separated from your model

you code will look something like ..

public class MonsterFactory
{
    private readonly Monster[] _monsters;

    public MonsterFactory(Monster[] monsters)
    {
        _monsters = monsters;
    }

    public Monster CreateMonster(MonsterType monsterType)
    {
        return _monsters.First(e => e.MonsterName == monsterType);
    }
}

public enum MonsterType
{
    Dragon,
    Beast
}

public class Monster
{
    public MonsterType MonsterName { get; set; }
    public int HitPoints { get; set; }
}

and the call would be like

var dragon = new MonsterFactory(listOfMonsters).CreateMonster(MonsterType.Dragon);

Hope this helps

Chintana Meegamarachchi
  • 1,798
  • 1
  • 12
  • 10