#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();
        }
    }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: