#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);
Hi Sean,
can you explain this a little further: // Prevent early instantiation due to beforefieldinit flag
Also why not just make a static method instead of Singleton Pattern?
There are sometimes advantages that argue for a singleton over just doing static methods, e.g. being able to treat the factory as an actual object. See http://www.dotnetperls.com/singleton-static for a nice comparison.
Adding a static constructor ensure that the beforefieldinit flag is not set by the compiler, which allows for lazier instantiation. See http://csharpindepth.com/Articles/General/BeforeFieldInit.aspx
If you mark the instance field read only and set it in the static constructor it is then thread safe. See http://csharpindepth.com/Articles/General/Singleton.aspx#cctor