#821 – The Factory Pattern
April 12, 2013 3 Comments
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.
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:
Dog myDog = DogFactory.Instance.CreateDog("Kirby", 15);