In software learning, singleton design pattern is a software design pattern which ensures that a class of any one object has only one instance (of computer science). In other words we can also say that it restricts the instantiation of class of any object. We require singleton pattern because it may sometimes happen that we require only one object to coordinate with the action across the system. This concept is also applicable when we have to restrict instantiation over a number of objects.
The singleton pattern helps us to solve problems like:
- Helps to ensure that a class has one instance.
- Helps to access the sole instance of a class easily.
- Helps to a class to control its instantiation.
- Helps to restrict number of instances of a class.
Now, you might be thinking how to solve such problems. Here are few key points which might help you:
- First key point is to make a class which is responsible by itself for controlling its instantiations.
- Second point is to hide the constructor (those objects which are created from classes by subroutines) of a class. This is important to do because by doing this you declare privacy that ensures the class would never be instantiated from outside of the class.
- Last point is to define a public static operation (for eg. , getInstance()) as this would return the sole instance of the class and is also easily accessible by using class name and operation name.
Another question might strike you, when to use Singleton? Here is the answer for that, you need to use Singleton when you find that this criteria mentioned below are satisfying:
- There must be ownership of single instance.
- There is no provision of global access.
- And there is lazy initialization (kind of lazy evaluation of instantiation of objects/classes).
Abstract factory, builder and prototype pattern use singleton pattern for their implementations. State objects and façade objects are also singletons. The reason behind why Singleton patterns are more preferable than compared to global variables is that while using Singleton pattern at that time you are sure enough how many number of instances you are working with and you can change your mind and manage any number of instances you want to.
Here is the syntax of Singleton implementation in two very known languages Java & C#:
Singleton implementation in Java
public final class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
Singleton implementation in C#
public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton Instance { get { if (instance == null) { instance = new Singleton(); } return instance; } } }