Design Patterns#4 Singleton Pattern

Burak KOCAK
2 min readFeb 5, 2023

--

Design Patterns

The Singleton pattern is a creational design pattern in Java that ensures a class has only one instance while providing a global point of access to this instance. The purpose of the Singleton pattern is to ensure that a class can only have one instance, while providing a single point of access to that instance.

The Singleton pattern is typically implemented by creating a private constructor in the class, ensuring that it can only be instantiated within the class, and then using a static method to return the single instance of the class. This method creates an instance of the class the first time it’s called and then returns the same instance for all subsequent calls.

Here’s a simple example of the Singleton pattern in Java:

class Singleton {
private static Singleton instance = null;

private Singleton() {}

public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

public class SingletonExample {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();

System.out.println(singleton1 == singleton2); // Output: true
}
}

In this example, the Singleton class has a private constructor and a public static method getInstance that returns the single instance of the class. The first time the getInstance method is called, it creates a new instance of the Singleton class and returns it. For all subsequent calls to getInstance, it returns the same instance that was created the first time. In the main method, we call Singleton.getInstance twice, and the == operator returns true, indicating that both variables refer to the same instance of the Singleton class.

--

--