SrcForge

Lesson 29

Singleton Class

A Singleton Class allows only one object to be created. The constructor is private, a static variable holds the instance and a public static method provides access.

Java Track

Save progress as you learn.

61 lessons

Lesson content

A Singleton Class in Java is a class that allows only one object to be created throughout the application's lifecycle. It provides a single global access point to that instance, ensuring controlled access to shared resources.

What is a Singleton Class in Java?

  • Allows only one instance of itself.
  • Provides global access to that instance.
  • Prevents direct object creation from outside the class.
  • Creates the instance only when needed.

Definition List

  • Singleton Class: A class that restricts object creation to a single instance and provides a global access point to it.
  • Instance: A runtime object created from a class.
  • Private Constructor: A constructor that prevents objects from being created outside the class.
  • Static Member: A class-level variable or method shared by all objects of the class.
  • Design Pattern: A reusable solution to a commonly occurring software design problem.

Why Use a Singleton Class?

  • Only one object is needed throughout the application.
  • Shared resources must be managed centrally.
  • Memory usage needs to be optimized.
  • Consistent access to configuration or service objects is required.

Common Use Cases

  • Database connection managers
  • Logging services
  • Configuration managers
  • Cache managers
  • Printer spoolers

How to Create a Singleton Class in Java

  1. Make the Constructor Private: Prevents other classes from creating objects using the new keyword.
  2. Create a Static Instance Variable: The class stores its only instance in a static variable.
  3. Provide a Public Static Method: The method returns the single instance of the class.

Example 1: Basic Singleton Structure

class ABC {
    static ABC obj = null;  // static member

    private ABC() {}  // private constructor

    public static ABC getInstance() {
        if (obj == null) {
            obj = new ABC();
        }
        return obj;
    }
}

// Usage
ABC in = ABC.getInstance();
in.display();

Example 2: Singleton Class Program

public class singletonClass {
    private static singletonClass instance;

    // Private constructor
    private singletonClass() {}

    // Public access method
    public static singletonClass getInstance() {
        if (instance == null) {
            instance = new singletonClass();
        }
        return instance;
    }

    public double calculateTriangleArea(double base, double height) {
        return 0.5 * base * height;
    }

    public double calculateSquareArea(double side) {
        return side * side;
    }

    public static void main(String[] args) {
        singletonClass calculator = singletonClass.getInstance();

        double triangleArea = calculator.calculateTriangleArea(5.0, 4.0);
        System.out.println("Area of the triangle: " + triangleArea);

        double squareArea = calculator.calculateSquareArea(6.0);
        System.out.println("Area of the square: " + squareArea);
    }
}

How the Program Works

  1. private static singletonClass instance — stores the single object of the class.
  2. private singletonClass() — private constructor prevents external classes from using new.
  3. getInstance() — checks if instance is null, creates it if so, then returns it every time.
  4. singletonClass.getInstance() — used instead of new to obtain the object.

Output

Area of the triangle: 10.0
Area of the square: 36.0

Advantages of Singleton Class

  • Memory Efficient: Only one object is created and reused.
  • Global Access: The instance can be accessed from anywhere in the application.
  • Better Resource Management: Useful for managing shared resources like database connections.
  • Controlled Object Creation: Prevents unnecessary object creation.

Limitations of Singleton Class

  • Can make unit testing more difficult.
  • May introduce tight coupling between classes.
  • Requires extra care in multithreaded applications.
  • Global state can become difficult to manage in large projects.

Singleton Class vs Normal Class

  • Number of Objects — Singleton: One. Normal: Multiple.
  • Constructor Access — Singleton: Private. Normal: Public.
  • Memory Usage — Singleton: Lower. Normal: Higher.
  • Global Access — Singleton: Yes. Normal: No.
  • Object Creation — Singleton: Controlled. Normal: Unrestricted.

Best Practices

  • Keep the constructor private.
  • Use a static method to provide access.
  • Consider thread-safe implementations in multi-threaded applications.
  • Use Singleton only when a single shared instance is truly required.

FAQ

1. What is a Singleton Class in Java?

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

2. Why is the constructor private in a Singleton Class?

The private constructor prevents other classes from creating additional objects using the new keyword.

3. Where is the Singleton Design Pattern used?

Singleton is commonly used in database connections, logging systems, configuration management, caching and resource management applications.

Singleton allows only one object of a class.
Constructor must be private.
Static variable holds the single instance.
getInstance() provides global access.
Object is created only when first needed.
Saves memory by reusing one object.
Used in DB connections, logging and caching.

Where Java is used

Java in real-world development

Singleton Class

Only one instance allowed. Provides a global access point to that instance.

Private Constructor

Blocks external object creation using new. Core of the Singleton pattern.

Static Instance

Class-level variable that holds the single shared object.

getInstance()

Creates the instance if null, then returns the same object every time.

Use Cases

Database connections, logging, config management, caching, printer spoolers.

Limitation

Harder to unit test. Needs thread-safe handling in multithreaded apps.