Skip to main content

How to Write a Singleton Class in Java: A Beginner's Guide

A singleton class is a class that can only have one instance throughout the entire application. This can be useful for creating objects that need to be shared across multiple components, such as database connections or configuration settings.

Principles of Singleton Design Pattern

The principles behind singleton design pattern are:

  • The class must have a private constructor to prevent instantiation from outside the class.
  • The class must have a static instance variable that holds the only instance of the class.
  • The class must have a public static method that returns the instance of the class.

Example of a Singleton Class


public class Singleton {
    private static Singleton instance;
    
    private Singleton() {
        // Private constructor to prevent instantiation from outside
    }
    
    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        
        return instance;
    }
}

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

In the above example, the Singleton class has a private constructor to prevent instantiation from outside the class. It also has a static instance variable, which is the only instance of the class, and a public static method that returns the instance of the class. The getInstance() method checks if the instance is null, and if it is, it creates a new instance. If it is not null, it returns the existing instance.

The Main class creates two instances of the Singleton class using the getInstance() method and checks if they are the same instance by comparing their memory addresses.

Comments