Member-only story

Singleton Pattern : Exploring the Enigma in Java

Rasathurai Karan
2 min readMay 2, 2023

--

Imagine you have a chocolate factory, and you want to make sure that there is only one instance of the factory in your town. This is where the Singleton design pattern comes in. It ensures that there is only one instance (object) of a class created throughout your program.

In Java, you can implement the Singleton design pattern using the following steps:

  1. Create a class called ChocolateFactory (or any other suitable name) and make its constructor private. This prevents other classes from directly creating instances of the class.
public class ChocolateFactory {
private static ChocolateFactory instance;

// Private constructor to prevent direct instantiation
private ChocolateFactory() {
}
}

2.Create a static method called getInstance() in the class. This method will be responsible for creating the single instance of the class and returning it.

public class ChocolateFactory {
private static ChocolateFactory instance;

// Private constructor to prevent direct instantiation
private ChocolateFactory() {
}

// Static method to get the instance
public static ChocolateFactory getInstance() {
if (instance == null) {
instance = new ChocolateFactory();
}
return instance;
}
}

--

--

No responses yet