#786 – A Lazier Singleton Pattern
February 22, 2013 2 Comments
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(); } }
Pingback: Dew Drop – February 25, 2013 (#1,504) | Alvin Ashcraft's Morning Dew
Pingback: #823 – A Nested Factory Class Implemented as a Singleton | 2,000 Things You Should Know About C#