Example Factory Method
To show a simple example of the factory method design pattern in action, we will create two factories that generate car objects. Each factory will be responsible for a different manufacturer of car. The generated objects could be objects that represent cars in a racing game.
public abstract class CarFactory
{
public abstract Car CreateCar(string model);
}
public class HyundaiCarFactory : CarFactory
{
public override Car CreateCar(string model)
{
switch (model.ToLower())
{
case "coupe": return new HyundaiCoupe();
case "i30": return new HyundaiI30();
default: throw new ArgumentException("Invalid model.", "model");
}
}
}
public class MazdaCarFactory : CarFactory
{
public override Car CreateCar(string model)
{
switch (model.ToLower())
{
case "mx5": return new MazdaMX5();
case "6": return new Mazda6();
default: throw new ArgumentException("Invalid model.", "model");
}
}
}
public abstract class Car { }
public class HyundaiCoupe : Car { }
public class HyundaiI30 : Car { }
public class MazdaMX5 : Car { }
public class Mazda6 : Car { }
Testing the Factory Method
The above implementation of the factory method pattern can now be tested. The following sample code uses one of the factories to create a new Car object using a parameter that could have been selected by the player at run-time. When the object's underlying type is outputted, we can see that the correct car subclass was selected.
CarFactory hyundai = new HyundaiCarFactory();
Car coupe = hyundai.CreateCar("coupe");
Console.WriteLine(coupe.GetType()); // Outputs "HyundaiCoupe"
11 July 2008