The Singleton pattern is one of the simplest design patterns in Java. This type of design pattern is a creation pattern because this pattern provides one of the best ways to create objects. (Recommended learning: java course )
This pattern involves a class that is responsible for creating an object while ensuring that only one object is created. This class provides a way to access its unique objects, which can be accessed directly without the need to instantiate an object of the class.
Implementation Example
We will create a single object class - SingleObject. The constructor of the SingleObject class is private and has its own static instance.
The SingleObject class provides a static method to obtain its static instance to the outside world. SingletonPatternDemo or sample class will use SingleObject class to get SingleObject 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 unique object from 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
Verify the output and get the following results -
Hello World!
The above is the detailed content of What is the singleton pattern in Java?. For more information, please follow other related articles on the PHP Chinese website!