3
\$\begingroup\$

I'm currently attempting to implement a factory method pattern for creating multiple different enemies after loading data from a file. But I'm having second thoughts on what would be the best design pattern to implement or if in fact I am even using it correctly, below is how I intended to use it:enter image description here

The Enemyfactory determines which enemy to create according to enemy type specified in the xml level file. For example:

<enemy>
    <type>
    NORMAL
    </type>
   ...
</enemy>

<enemy>
    <type>
    BRAWLER
    </type>
   ...
</enemy>

This data is read in the LevelLoader and then can be used to construct enemies. In the LevelLoader class I could easily have somehting like this instead:

if(node.equal("NORMAL")){
 return new NormalEnemy(//parameters from file to construct enemies);
  }else if (node.equal("BRAWLER")) {
  return new BrawlerEnemy();
}

With this information, what would be the best way/best design pattern to use to create multiple enemies.

\$\endgroup\$

2 Answers 2

5
\$\begingroup\$

Not only you can encapsulate the mechanisms of object creation into Factory, but you can use Decorator pattern to define flexible enemy structure. Because you use a xml to define object structure, it would be very flexible to define a bunch of decorators and to play with them in the xml. Possible class diagram for enemy composition: enter image description here

I can't define behaviour of decorators for now, because I don't know the responsibilities of your enemies, but as far as I can see decorators would escalate render call to wrapped object, but add some behavior on update method. In addition, you can consider creating other principal classes besides NormalEnemy.

You can also examine using Composite pattern or similar way in dealing with this complexity, which if described in this article: Refactoring Game Entities with Components

\$\endgroup\$
2
  • \$\begingroup\$ +1 for link, decorator/composition is the proper way to go. \$\endgroup\$
    – Kyle C
    Commented Jan 4, 2013 at 0:36
  • \$\begingroup\$ Coming back to this after a while and this makes a lot of sense, thanks. \$\endgroup\$
    – Sun
    Commented Dec 27, 2014 at 15:52
2
\$\begingroup\$

You can use factory method or you can use array of objects prototype pattern (prototypes or templates, how to name them your choice) from which you create objects just copying and instantiating if required. I've seen only this two ways of problem solution, if someone suggest another one I'll be glad to see them (possibly they are better)

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .