Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.
Example:
Suppose you have an exam and you need to use a calculator, but you don’t have one. So, you go to the market and buy a calculator, then use it on your exam. Next time when you have another exam that requires a calculator, you will not buy a new one. You will use your old one. This way, you can save your money. The singleton pattern works in a similar way.
Code Example:
public class Calculator {
static Calculator single_instance = null;
private Calculator(){};
static Calculator create_instance(){
if(single_instance == null)
{
single_instance = new Calculator();
}
return single_instance;
}
void printCalculator(){
System.out.println("Calculator Used");
}
}
import java.util.*;
public class MainActivity {
public static void main(String[] args) {
Calculator c1 = Calculator.create_instance();
c1.printCalculator();
}
}
Explain:
The singleton design pattern is a way of ensuring that a class has only one instance and provides a global point of access to it. The benefits of using this pattern are that it saves memory, avoids synchronization issues, and allows centralized control of the instance.
The code you have shown is an example of implementing the singleton pattern in Java using a static factory method and a private constructor. The static factory method (create_instance()) returns the single instance of the Calculator class, and the private constructor prevents other classes from creating new instances of Calculator. The static field (single_instance) holds the only instance of Calculator and is initialized lazily, meaning it is created only when needed.
The code works by following these steps:
When the main method of MainActivity class is executed, it calls the create_instance() method of Calculator class.
Since the single_instance field is null at this point, the create_instance() method creates a new Calculator object and assigns it to single_instance.
The create_instance() method then returns the single_instance object to the main method, which assigns it to a local variable c1.
The main method then calls the printCalculator() method on c1, which prints “Calculator Used” to the console.
If the main method calls the create_instance() method again, it will not create a new Calculator object, but return the existing one stored in single_instance. This ensures that only one instance of Calculator exists throughout the program.