Design Patterns

Implementing the Singleton Pattern in Java

August 9, 2023

Implementing the Singleton Pattern in Java

The Singleton pattern is one of the simplest yet most powerful design patterns in object-oriented programming. It ensures that a class has only one instance and provides a global point of access to that instance.

Why Use the Singleton Pattern?

  • Single Instance: Guarantees that a class has only one instance
  • Global Access: Provides a global point of access to that instance
  • Lazy Initialization: The instance is created only when it's needed

Basic Implementation

public class Singleton { // Private static instance variable private static Singleton instance; // Private constructor to prevent instantiation private Singleton() { // Initialization code } // Public static method to get the instance public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } // Other methods public void doSomething() { System.out.println("Singleton is doing something"); } }

Thread-Safe Implementation

The basic implementation is not thread-safe. Here's a thread-safe version:

public class ThreadSafeSingleton { private static volatile ThreadSafeSingleton instance; private ThreadSafeSingleton() { // Initialization code } public static ThreadSafeSingleton getInstance() { if (instance == null) { synchronized (ThreadSafeSingleton.class) { if (instance == null) { instance = new ThreadSafeSingleton(); } } } return instance; } }

Enum Singleton

Java's enum provides a thread-safe and serialization-safe singleton implementation:

public enum EnumSingleton { INSTANCE; // Add methods and fields public void doSomething() { System.out.println("EnumSingleton is doing something"); } } // Usage EnumSingleton.INSTANCE.doSomething();

When to Use the Singleton Pattern

The Singleton pattern is useful when:

  1. There must be exactly one instance of a class
  2. The instance must be accessible from a well-known access point
  3. The sole instance should be extensible by subclassing

Common examples include configuration managers, connection pools, and caches.