#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");
Pingback: #786 – A Lazier Singleton Pattern | 2,000 Things You Should Know About C#
Pingback: #948 – Using Lazy to Implement the Singleton Pattern | 2,000 Things You Should Know About C#
If a second line is added:
Dog d2 = DogFactory.Instance.CreateDog(“Sam”);
It creates a second dog, right? So what is the benefit please?
You can create as many Dog instances as you like–that’s what the DogFactory class does. But you’re only allowed to create a single instance of the DogFactory–that’s the class that follows the singleton pattern.
Thanks,. how to handle multi threaded scenario, no need to lock it?