#786 – A Lazier Singleton Pattern

Ideally, you’d want the implementation of a singleton to be as “lazy” as possible, i.e.–create the instance as late as possible, just prior to when you need it.  This helps performance, since we only create the object if/when we need it.

In our earlier implementation, the instance of our class gets created whenever any of the static members of our class are accessed.  This might be when we first access the Instance property, but might be earlier, if we had other static members in the class.

Below is a Singleton pattern that is a bit lazier.

    public sealed class DogFactory
    {
        // Prevent instantiation
        private DogFactory() { }

        public static DogFactory Instance
        {
            get { return InstanceContainer.instance; }
        }

        private class InstanceContainer
        {
            // Prevent early instantiation due to beforefieldinit flag
            static InstanceContainer() { }

            internal static readonly DogFactory instance = new DogFactory();
        }
    }

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

2 Responses to #786 – A Lazier Singleton Pattern

  1. Pingback: Dew Drop – February 25, 2013 (#1,504) | Alvin Ashcraft's Morning Dew

  2. Pingback: #823 – A Nested Factory Class Implemented as a Singleton | 2,000 Things You Should Know About C#

Leave a comment