Quantcast
Channel: 2,000 Things You Should Know About C# » Patterns
Viewing all articles
Browse latest Browse all 9

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

$
0
0

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.


Filed under: Patterns Tagged: C#, Lazy, Lazy Instantiation, Patterns, Singleton

Viewing all articles
Browse latest Browse all 9

Latest Images

Trending Articles





Latest Images