What is Singleton Class in java?

A singleton class in Java is a class that allows only one instance to be created throughout the lifetime of an application. It’s a design pattern used when exactly one object is needed to coordinate actions across the system—like a single configuration manager, logger, or database connection pool.

🧱 Key Characteristics of a Singleton Class

  1. Private Constructor: Prevents external instantiation.
  2. Static Instance: Holds the single instance of the class.
  3. Public Static Method: Provides global access to the instance.

🧪 Example: Classic Singleton Implementation

// Singleton class
public class Singleton {
    // Step 1: Create a private static instance variable
    private static Singleton instance;

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

    // Step 3: Public synchronized method to provide access to the instance
    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton(); // Lazy initialization
        }
        return instance;
    }

    // Example method
    public void showMessage() {
        System.out.println("Hello from Singleton!");
    }
}

🧪 Test Class to Demonstrate Singleton

public class Main {
    public static void main(String[] args) {
        // Get the only object from Singleton class
        Singleton obj1 = Singleton.getInstance();
        obj1.showMessage();

        // Try to get another instance
        Singleton obj2 = Singleton.getInstance();
        obj2.showMessage();

        // Check if both references point to the same object
        System.out.println("Are both instances the same? " + (obj1 == obj2));
    }
}

🧾 Output:

Singleton instance created. Hello from Singleton! Hello from Singleton! Are both instances the same? true

This confirms that only one instance of the class is created and reused.

🧠 Why Use Singleton?

  • Resource Sharing: One shared object (e.g., database connection).
  • Global Access Point: Easy to access from anywhere.
  • Controlled Access: Centralized control over the instance.

⚠️ Caution: Thread Safety

In multi-threaded environments, the above implementation can create multiple instances. To fix this, you can:

  • Use synchronized keyword.
  • Use double-checked locking.
  • Use eager initialization.
  • Or the most elegant: Enum Singleton (thread-safe by default).

🧩 Real-World Use Case

“In my automation project, I used a Singleton class to manage the WebDriver instance. This ensured that only one browser session was active at a time, avoiding conflicts and saving resources.”

🔧 Step 1: Create the Singleton WebDriver Class

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class DriverManager {
    private static DriverManager instance = null;
    private WebDriver driver;

    // Private constructor to prevent instantiation
    private DriverManager() {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }

    // Public method to provide access to the instance
    public static DriverManager getInstance() {
        if (instance == null) {
            instance = new DriverManager();
        }
        return instance;
    }

    public WebDriver getDriver() {
        return driver;
    }

    public void quitDriver() {
        if (driver != null) {
            driver.quit();
            driver = null;
            instance = null;
        }
    }
}

🧪 Step 2: Use It in Your Test Class

import org.openqa.selenium.WebDriver;

public class TestExample {
    public static void main(String[] args) {
        WebDriver driver = DriverManager.getInstance().getDriver();
        driver.get("https://www.example.com");

        // Perform your test steps here...

        // Quit the driver after test
        DriverManager.getInstance().quitDriver();
    }
}

✅ Benefits

  • Ensures only one browser instance is active.
  • Prevents resource leaks and driver conflicts.
  • Makes your framework cleaner and more maintainable.

Leave a Reply

Your email address will not be published. Required fields are marked *