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#.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| 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:
1
| Dog d = DogFactory.Instance.CreateDog("Bob"); |

