#821 – 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.

    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);

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #821 – The Factory Pattern

  1. metacircle says:

    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?

  2. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: