Singleton Class in Java – Definition, Syntax, and Example

Singleton Class in Java – Definition, Syntax, and Example

Singleton Class in Java – Definition, Syntax, and Example

The Singleton Class in Java is a design pattern that ensures only one instance of a class exists throughout the application. This is particularly useful when exactly one object is needed to coordinate actions across the system.

Definition

A Singleton Class is a class that allows only a single instance to be created and provides a global point of access to that instance.

Key Points of Singleton Class

  • Only one instance of the class is created.
  • Provides a global access point.
  • Can be implemented using Eager Initialization or Lazy Initialization.
  • Thread safety is important for multi-threaded applications.

Syntax

class Singleton {
    // Private static instance
    private static Singleton singleInstance = null;

    // Private constructor to prevent instantiation
    private Singleton() {
        System.out.println("Singleton instance created");
    }

    // Public static method to get the instance
    public static Singleton getInstance() {
        if (singleInstance == null) {
            singleInstance = new Singleton();
        }
        return singleInstance;
    }
}
  

Example Usage

public class Main {
    public static void main(String[] args) {
        // Both instances will refer to the same object
        Singleton obj1 = Singleton.getInstance();
        Singleton obj2 = Singleton.getInstance();

        if (obj1 == obj2) {
            System.out.println("Both refer to the same instance");
        }
    }
}
  

Advantages of Singleton Pattern

  • Controls concurrent access to resources.
  • Reduces memory usage by reusing the same instance.
  • Provides a centralized way to manage shared data.

Disadvantages of Singleton Pattern

  • Difficult to unit test due to global state.
  • Can lead to tightly coupled code.
  • Not suitable for scenarios requiring multiple instances.

Frequently Asked Questions (FAQ)

Q1: Why use Singleton in Java?

To ensure that only one instance of a class exists and to provide global access to it.

Q2: Is Singleton thread-safe?

It depends on the implementation. Use synchronized blocks or other techniques for thread safety.

Q3: Can we clone a Singleton object?

No, you should override the clone() method to prevent cloning.

Comments

Popular posts from this blog

Introduction to Java

Java Classes in Depth – Complete Guide with Definitions, Syntax & Examples

Top AI Tools for Social Media Marketing in 2025 – Automate & Grow Your Brand