Search code examples
design-patternsobject-construction

Need a design pattern to remove enums and switch statement in object creation


Let's say I am creating a sports game, and in this game there are various positions a player can play, attack, defence, etc. So I start by creating a base class:

public abstract class Position
{
 public abstract string Name
 {
  get;
 }
}

and the subclasses...

public class Defender : Position
{
 public override string Name
 {
  get { return "Defender"; }
 }
}

and so on. This is all fine.

But now I need a function to create these objects. I need a create by position function. So one possible solution is to create an enum of all the positions and pass this value to a function that switches on the enum and returns the appropriate object. But this triggers my code smell alarm. This soultion ties together the classes, the enum and the switch inside a function:

public static Position GetByType(Types position)
{
 switch(position)
 {
  case Types.Defender:
   return new Defender();
... and further terrible code

What solution should I be looking at? Which design pattern is this?


Solution

  • If you have to do this on a small scale, the switch isn't really bad, especially if it lives in a single place.

    If you have to do this on a medium scale, you might want to consider improving the internals a bit -- Steve Ellinger's suggestion is a reasonable one. Personally I prefer to use a IDictionary<MyEnum, Action<T>> where the Action returns a new instance of the class in question.

    If you have to do this on a grand or configurable scale, you should probably check out an IoC controller such as structuremap or ninject or whatever the cool kids are playing with these days.