Singleton Design Pattern
This pattern is used where only one instance of the object is required and shared among all the clients. The same instance is maintained throughout the entire life cycle of the class object. This is not handled by the client code rather it is the responsibility of the class to make sure that only one intsance exists throughout all the client calls.
So how this is possible? If I have access to the class I can create as many instances by just using new.
That is not true. If I make the constructor private, I can not create object using new.
But then how I will get the object? This is further done by exposing a public static GetInstance (you can give it any meaningful name) method/property.
- A private static variable of the Singleton Class type is defined and intantiated in the private static constructor of the class. So when a call occurs to the GetInstance method this same static object is returned.
- Also as best practice it is ensured that private static instance variable is instantiated only when it is required.
- Also there exist thread safe version of this Singleton Class by putting a lock while instantiating the class object. We also mark singleton class as sealed to make it more safe, so that no subclass can attempt to intantiate and get more that one instance.
- It makes sure that only one instance of the class exists
- Can get access to data in this class from anywhere
- Acts like global variable
- Can cause methods to have unintended and unintefied side effects due to data sharing via state in the singleton
Steps to implement Singleton Pattern:
- Make constructor private
- Add a private static object which will be internally instantiate using the private static constructor
- Add a public static property which will return the instance of the class