[Design Patterns] Factory

A factory is an object for creating other objects. A factory object typically has a method to create any specific object and return the reference to it. These methods optionally accept parameters defining how the object is created.

 

1. Factory

The “Factory” pattern defines a mechanism for creating an object of one of possible classes depending on the data provided to it. It is also called as a “Factory Method” or a “Virtual Constructor“.

 

2. Design

 

3. Implementation

  • abstract super class
  • several sub classes
  • a class with a factory method, such as “getInstance()”, which is sometimes static

 

4. Consequences

  • centralizes the knowledge of which class is created
  • elimiates the need to bind application-specific classes into the code

 

5. Example

Suppose we need monsters in the game programming.

public abstract class Monster
{
  public String Name { get; set; }
  public int Life { get; set; }
  public int LifeRemaining { get; set; }
  public int HitPoint { get; set; }

  public abstract void move();
  public abstract void attack();
}

public class Orge : Monster
{
  public override void move()
  {
    Console.WriteLine("Orge is moving.");
  }
  public override void attack()
  {
    Console.WriteLine("Orge is attacking.");
  }
}

public class Spawn : Monster
{
  public override void move()
  {
    Console.WriteLine("Spwan is moving.");
  }
  public override void attack()
  {
    Console.WriteLine("Spwan is attacking.");
  }
}

 

public class MonsterFactory
{
  public static Monster getMonster(int type)
  {
    if ( type == 1 ) // weak monster
    {
      return new Spawn
      {
        Name = "Spawn", Life = 100, LifeRemaining = 100, HitPoint = 10
      };
    }
    else if ( type == 2 ) // strong monster
    {
      return new Orge()
      {
        Name = "Orge", Life = 500, LifeRemaining = 500, HitPoint = 50
      };
    }
    else // invalid type - return null
    {
      return null;
    }
  }
}

 

// Create a spawn Monster
monster1 = MonsterFactory.getMonster(1);
Console.WriteLine("The {0} is created.", monster1.Name);

// Create an orge Monster
monster2 = MonsterFactory.getMonster(2);
Console.WriteLine("The {0} is created.", monster2.Name);

monster1.move();
monster2.attack();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s