Creational Design Patterns in C# - Singleton Pattern
Singleton Pattern
Singleton Pattern
Singleton pattern (wiki) is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to be shared across the system.
To make a class Singleton, usually the below pattern is followed:
The constructor of the class is made ‘private’. Only one constructor is implemented. With single private constructor, it cannot be instantiated from any client code. |
A static private variable is declared that will hold the only instance of class to be created. |
A public static method returning the above private variable that is holding the instance of the class. Inside this method, a check is made if the above variable is null, and if it is null, its assigned to a new instance of the class created using its private constructor. |
Some also prefer to decorate the class with ‘sealed’ modifier to let compiler know explicitly that this class cannot be instantiated. |
There are many examples of Singleton patterns available online, I found this one in particular very well explained.
Previous: Prototype Pattern |
You might also be interested in these articles...