I went through a lot of articles and books and here trying to make it simple to understand the concept and use of singleton design pattern in real scenarios.
Undetstanding Singleton Design Pattern
In real world scenario Singleton Design Pattern is used where there is need of sharing a single object resource within scope with multiple clients restricting the creation of object for each method call.
Singleton design pattern belongs to creational pattern as it deal with object creation and manipulation.
where to use the Singleton design pattern.
1. when it is required to share a resource with multiple clients simultaneously.
2. when lazy- loading is required with static method Initialization.
3. In-Memory caching of static data is required.
4. when it is not required to create a new object every-time to get the static data.
How to implement in a class :
1. Declared as sealed class – so it cannot be inherited.
2. Create a private and parameterless constructor – so it cannot be instantiated from outside the class and can only be instantiates from within the class.
3. Create a private static variable – to hold a reference to the single created object instance of the class.
4. create a public static property/method – to create a instance of the singleton class. ( This method or property first check if an instance of the singleton class is available or not. If the singleton instance is available, then it returns that singleton instance otherwise it will create an instance and then return that instance.)
C# code to create a class to implement singleton design pattern by following the above understandings.