What is Singleton Class?

A Singleton class is a design pattern that ensures only one instance of a class is created throughout the application's lifecycle. It provides a single global access point to that instance, making it useful for managing shared resources such as configuration settings, logging services, and database connection managers.

Key Points: • A Singleton class allows only one object to exist in the JVM for that class. • The constructor is made private to prevent object creation from outside the class. • A static method is provided to access the single instance. • It helps conserve resources when only one shared object is required. • Common use cases include configuration management, caching, logging, and connection pools.

Example: In an application, configuration settings should be loaded only once and shared across all modules. Creating multiple configuration objects would waste memory and may lead to inconsistent data. A Singleton ensures a single shared instance.

Code Example:

public class Singleton {

    private static Singleton instance;

    private Singleton() {
    }

    public static Singleton getInstance() {

        if (instance == null) {
            instance = new Singleton();
        }

        return instance;
    }
}

public class Demo {

    public static void main(String[] args) {

        Singleton obj1 = Singleton.getInstance();
        Singleton obj2 = Singleton.getInstance();

        System.out.println(obj1 == obj2);
    }
}

Output:

true

Advantages: • Ensures a single instance of a class • Saves memory and resources • Provides centralized access to shared data • Useful for application-wide services

Interview Tip: A concise interview answer is:

"A Singleton class is a class that allows only one instance to be created and provides a global access point to that instance. It is commonly used for shared resources such as configuration managers, loggers, and database connection managers where multiple instances are unnecessary."