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