#948 – Using Generic Lazy Class to Implement the Singleton Pattern

The singleton pattern is useful in cases when you only want/need a single instance of a type, e.g. to use in creating instances of some other type (an object factory).

We can make use of the Lazy<T> type to implement a singleton that is created as late as possible, i.e. just before it is used.

    public sealed class DogFactory
        // Instance created when first referenced
        private static readonly Lazy<DogFactory> instance =
            new Lazy<DogFactory>(() => new DogFactory());

        // Prevent instantiation
        private DogFactory() { }

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

        // Actual methods go here, e.g.:
        public Dog CreateDog(string name)
            return new Dog(name);

Notice that we can access other static members of the DogFactory without forcing the instance object to get created. The instance will only be instantiated when we use the Instance property.


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

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 )

Connecting to %s

%d bloggers like this: