Description
The Singleton design pattern is one of the Creational Design Patterns, which makes sure only one object is created for a class.
- It is one of the simplest design patterns.
- It provides one of the best ways to create an object.
- It involves a single class that is responsible for creating an object while making sure that only one object is created.
- The class provides a way to directly access its only object without instantiation.
Implementation in Java
Let's follow the below approach to implement this design pattern in Java.
- Create a class "SingleObject", with a private constructor that has a static instance of itself.
- Contains a static method to get its static instance outside the class.
- Create a class "SingletonPatternDemo" that contains the "main" method, that uses the "SingleObject" class to get an object.
- Contains the "main" method that uses the "SingleObject" class to get an object.
Step 1: Create a singleton class.
SingleObject.java
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
System.out.println("Hello World!");
}
}
Step 2: Get the only object using the singleton class.
SingletonPatternDemo.java
public class SingletonPatternDemo {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();
//Get the only object available
SingleObject object = SingleObject.getInstance();
//show the message
object.showMessage();
}
}
Step 3: Execute the code to verify the output.
Hello World!
Overall
We now know about the Singleton design pattern and its implementation.