Singleton Pattern in Java: What It Is and How It Works
Singleton pattern in Java ensures a class has only one instance and provides a global point of access to it. It is used to control object creation, limiting the number of instances to one.How It Works
The Singleton pattern works like a single remote control for a TV. Instead of having many remotes, you have just one that everyone uses. In Java, this means the class creates only one object and shares it everywhere.
When you ask for the object, the class checks if it already exists. If it does, it gives you the same one. If not, it creates it first. This way, you avoid making many copies and keep everything consistent.
Example
This example shows a simple Singleton class in Java. It uses a private constructor and a static method to get the single instance.
public class Singleton { private static Singleton instance; // holds the single instance private Singleton() { // private constructor stops others from creating new objects } public static Singleton getInstance() { if (instance == null) { // create instance if it doesn't exist instance = new Singleton(); } return instance; // return the single instance } public void showMessage() { System.out.println("Hello from Singleton!"); } public static void main(String[] args) { Singleton obj1 = Singleton.getInstance(); Singleton obj2 = Singleton.getInstance(); obj1.showMessage(); System.out.println("Are both objects the same? " + (obj1 == obj2)); } }
When to Use
Use the Singleton pattern when you need only one object to control something in your program. For example:
- Managing a connection to a database so all parts use the same connection.
- Controlling access to a printer or logging system.
- Keeping a global configuration or settings object.
This helps avoid conflicts and saves resources by not creating many copies of the same object.
Key Points
- Singleton restricts a class to one instance only.
- It provides a global access point to that instance.
- Uses a private constructor and a static method.
- Helps manage shared resources or configurations.