What is Singleton design pattern?
Singleton is a creational design pattern that is used to ensure that a class has only one instance, and provide a global point of access to that instance. This pattern is useful when we want to limit the number of instances of a class that can be created, or when we want to ensure that all objects of a certain class share a common state.
The singleton pattern involves creating a class with a private constructor, and a static method that returns the same instance of the class every time it is called. This method usually checks if an instance of the class has already been created, and if so, returns that instance. Otherwise, it creates a new instance and returns it.
Here is an example of a Singleton class in Java:
public class Singleton {
private static Singleton instance;
private Singleton() {
// private constructor to prevent instantiation from outside
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public void doSomething() {
// some code
}
}
In the above example, getInstance()
method returns the same instance of Singleton
class every time it is called. The doSomething()
method can be called on that instance to perform some operation.
Note that the above implementation of Singleton is not thread-safe. If multiple threads attempt to access the Singleton instance concurrently, it may lead to creation of multiple instances of Singleton. To make the Singleton implementation thread-safe, the getInstance()
method can be synchronized or we can use the double-checked locking approach to ensure that only one instance of the class is created.