Exploring the usage of singleton pattern and understanding the usage of static vs singleton..
Introduction
In this article I would like to share my understanding on singleton pattern and hope its useful to beginners.
Objective
Understanding singleton and its usage.
Using the code
In this article I want to address the following questions
- What is singleton?
- Why we need singleton?
- How to create a Singleton class?
- When to use singleton?
Ok. Now let’s face our first question.
1. What is singleton?
Singleton is a design pattern that falls into creational pattern category. This pattern focuses on creating an object only once. So the ground rule is at any point of time in the application runtime only one instance of a class will be created and used across the application.
That’s simple, now why we need it? don’t we have any other alternative? let’s explore…
2. Why we need singleton?
It’s a amazing question!. Can’t we achieve without this pattern?
To my knowledge I think creating a class as static can solve this as static class doesn’t allow to create an instance. When we create a class as static it forces you to define all your methods as static. And more over in case of singleton we can pass the instance to other methods and your code is well organized.
3. How to create a Singleton class?
In order to create a class as singleton we need to address the following things.
First thing we should restrict the class being instantiated. Let’s make the constructor of the class as “Private” so we can’t instantiate from other classes.
public class Singleton
{
private Singleton() { }
}
Ok, now we have restricted then how to make this class accessible to do our job? In order to achieve this expose a public static property through which the Instance of the Singleton class will be available.
public class Singleton
{
private static readonly Singleton Instance = newSingleton();
public static Singleton GetInstance
{
get { return Instance; }
}
private Singleton()
{
}
}
Here if you notice we have made the variable “Instance” as static read-only which is because it forces you to initialize either at variable declaration or at static constructor level.
Thus we have achieved implementing our class using singleton pattern. Now we need to think when this will be useful to answer our last question.
4. When to use singleton?
There are lots of places where this pattern will be helpful to name some of them, we can implement when implementing logger class or DatabaseConnection class or in thread model application etc.
Conclusion
I hope this article opens up a initial spark to explore Singleton pattern. Only one ground rule we need to consider "Only single instance" at any point of time.