Singleton design pattern in Java

Category : Java | Sub Category : Java Interview questions | By Prasad Bonam Last updated: 2023-07-08 20:49:22 Viewed : 76

Singleton design pattern

Certainly! Here is an example of the Singleton design pattern implemented in Java:

public class Singleton{
private static Singleton instance;
private String data;
private Singleton() {
// Private constructor to prevent instantiation from outside
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton(); }
} }
return instance; }
public void setData(String data) { = data; }
public String getData() {
return data;
} }

In this example, we have a Singleton class with a private constructor to prevent direct instantiation. The class has a static getInstance() method that returns the singleton instance. The instance is lazily initialized on the first call to getInstance().

The double-checked locking mechanism is used to ensure thread safety during the initialization of the instance. It ensures that only one instance is created even in a multi-threaded environment.

Here is how you can use the Singleton class:

public class Main {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
singleton1.setData("Hello, Singleton!");
// Output: Hello, Singleton!
System.out.println(singleton1 == singleton2);
// Output: true (same instance) }

In this example, singleton1 and singleton2 both refer to the same instance of the Singleton class. Modifying the data of one instance reflects the change in the other instance, demonstrating that they are indeed the same object.

The Singleton pattern ensures that there is only one instance of the class throughout the application and provides a global point of access to it. It is commonly used in scenarios where a single shared resource or a central manager needs to be accessed from multiple parts of the application.

Related Articles

Leave a Comment: