Singleton Class

Singleton Class

Introduction

Singleton class in Java basically a design pattern, that restrict the creation of more than one object of a class, that is needed when you want only one object to perform multiple actions across the system.

Basically with the help of Singleton class we make sure that it has only one instance and provide a global point of access to it.

Example : Logging - A Singleton class can help in creating logging method and can be access using instances of Singleton class because logging is generally required throughout the application so we can add that method into Singleton class.

Code for Singleton class

Below is the code how to create Singleton class

public class Singleton {
    // Static variable to hold the single instance of the Singleton class
    private static Singleton instance;

    // Private constructor to prevent instantiation from other classes
    private Singleton() {
    }

    // Public method to provide access to the single instance of the class
    public static Singleton getInstance() {
        // Check if the instance is null, meaning it hasn't been created yet
        if (instance == null) {
            // If null, create the instance
            instance = new Singleton();
        }
        // Return the single instance of the class
        return instance;
    }
}

Advantages of Singleton class

  • Controlled access to the single instance - The Singleton pattern provides a controlled way of creating a single instances of a class.

  • Reduce memory usage - It reduces the memory usage, especially if the instances is heavyweight object.

  • Global access point - Singleton instance provide global point of access to the instance.

Disadvantages of Singleton class

  • Concurrency issues - If not implemented correctly, Singleton can lead to concurrency issues.

Conclusion

The Singleton pattern is a powerful tool in Java that ensures a class has only one instance and provides a global point of access to that instance. When used appropriately, Singletons can greatly simplify the design and management of code.