Sitemap
kush bhatt

kush bhatt

Singleton Pattern In Java

2 min readJun 20, 2025

--

If you’re learning Java and heard about design patterns, the Singleton Pattern is one of the easiest and most useful to start with. It helps you make sure that only one object of a class is created during the entire program.

— —

What is Singleton Pattern?

> Singleton means “only one”.

The Singleton Pattern makes sure that:

Only one object of a class is created
That object is shared everywhere in the program

Think of it like having only one TV remote in a room — everyone shares it instead of creating new ones!

— -

Where Do We Use Singleton?

Some real-life examples in programming:

Logging (write to a single log file)

App settings or configuration (read once, use everywhere)

Database connection (one connection, reused)

— -

How to Create Singleton in Java?

Get kush bhatt’s stories in your inbox

Join Medium for free to get updates from this writer.

You need 3 simple steps:

1. Make constructor private (no one can create object from outside)

2. Create a static object of the class

3. Give a public method to access that object

— -

Easy Example to Explain

// logger.java to save this file

public class Logger {

// Step 1: Create a static variable to hold single object
private static Logger instance;

// Step 2: Make the constructor private
private Logger() {
System.out.println("Logger Started!");
}

// Step 3: Create a method to return the single object
public static Logger getInstance() {
if (instance == null) {
instance = new Logger(); // Create object only once
}
return instance;
}

public void log(String message) {
System.out.println("LOG: " + message);
}
}
// Main.java – Use the Singleton

public class Main {
public static void main(String[] args) {
// Get the logger object
Logger logger1 = Logger.getInstance();
logger1.log("First message");

// Try again
Logger logger2 = Logger.getInstance();
logger2.log("Second message");

// Check if both are same object
if (logger1 == logger2) {
System.out.println("Same logger used (Singleton works!)");
}
}
}

// OUTPUT
Logger Started!
LOG: First message
LOG: Second message
Same logger used (Singleton works!)

> Notice: Logger Started! printed only once — object created only one time!

— -

Remember

Only one object is made

Everyone uses the same object

Saves memory and controls resources

Conclusion

The Singleton Pattern is a fundamental design pattern that ensures only one instance of a class exists in the entire application, and provides a global access point to that instance.

--

--