The Factory Pattern

Factory is a design pattern that you can use when you don’t want client code creating objects directly, but you want to centralize object creation within another class.  To get a new instance of an object, you call a method in the factory, which creates the object on your behalf.
In the example below, DogFactory.CreateDog is a factory method, which does the actual creation of a Dog object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public sealed class DogFactory
{
    // Instance created when first referenced
    private static readonly DogFactory instance = new DogFactory();
 
    // Prevent early instantiation due to beforefieldinit flag
    static DogFactory() { }
 
    // Prevent instantiation
    private DogFactory() { }
 
    public static DogFactory Instance
    {
        get { return instance; }
    }
 
    // Factory pattern - method for creating a dog
    public Dog CreateDog(string name, int age)
    {
        return new Dog(name, age);
    }
}
To create a Dog:


1
Dog myDog = DogFactory.Instance.CreateDog("Kirby", 15);