Recently I added a post on the Factory Pattern in C#. Continuing on the same lines, I will be writing an example of another design pattern named Singleton Pattern. Like Factory pattern, this pattern is also Creational Pattern.
As the name suggests, this pattern implies that only one instance of the class can be created. All other calls have to be made using this one instance created.
To start with, let’s create a small sample for it. Create a new project and add following two class files
1. NormalClass.cs : This is a simple empty class like any other class that we create
2. SingletonClassSample.cs : This is the class for which we want only one instance to be created throughout the application.
3 points that help us understand this concept in a better way can be derived from the above declared Singleton sample class :
- The basic idea is to restrict the user to create more than one instance of the Singleton Class. In order to do this, we declare a Private constructor for this class.
- Next we want to provide a copy of instance. In order to do so, we declare our method to be Static. This will not require any instance creation to call the source method.
- This method will check if the instance is already initialized or not. If not, it will create an instance and return from the static method
Next, on the UI end, we add two buttons and a label to illustrate the functionality. Button1 will create the instances of the Singleton class and Button2 will create the instances of a normal Class. Then we compare the objects to check whether the same instance is being returned or a new instance is returned for both the classes. See the image below :
Run the application and click on button1, it will display the first condition i.e. “This is the singleton instance.”. Clicking on button2 will display “Two different class instances are created”.
One of the very good usage of this pattern could be in the ADO.Net where we create SqlConnection again and again. Instead of this, we can create a base Singleton class which returns the instance for this class(Not tried myself, but certainly feel it is a good option to go for). Hope it clears the basic rules/usage for you to understand them.
I have tried to provide these in a very simple manner & tried to cover all the important points related to them. So if you feel you can help improve this, or can contribute then suggestions/feedback are welcome.