BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Design Patterns
.NET 1.1+

Factory Method Design Pattern

The factory method pattern is a design pattern that allows for the creation of objects without specifying the type of object that is to be created in code. A factory class contains a method that allows determination of the created type at run-time.

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