#785 – The Singleton Pattern
February 21, 2013 5 Comments
Singleton is a design pattern that you can use when you have a situation where you want to limit a particular class to have at most one instance.
A singleton behaves similarly to a static class in C#, but has some advantages, in that it behaves as a traditional object. (E.g. Can implement an interface, or be passed to a method).
Here’s a common (thread-safe) pattern for implementing a singleton in C#.
public sealed class DogFactory { // Instance created when first referenced private static readonly DogFactory instance = new DogFactory(); // Prevent early instantiation due to beforefieldinit flag static DogFactory() { } // Prevent instantiation private DogFactory() { } public static DogFactory Instance { get { return instance; } } // Actual methods go here, e.g.: public Dog CreateDog(string name) { return new Dog(name); } }
To use the singleton, you use the Instance property:
Dog d = DogFactory.Instance.CreateDog("Bob");