DEV Community

Tommy
Tommy

Posted on

Singleton Design Pattern

The Singleton Design Pattern is a type of creational pattern that ensures a class has only one instance while providing a public access point to that instance.

This pattern is useful for preventing the repeated instantiation of resource-heavy objects and for objects needed to coordinate actions across the application system.

It is commonly used for things like database connection pools, logging, cache management, configuration classes, etc.

public class Singleton {

    // Create a private static instance of the class
    private static Singleton instance;

    // Make the constructor private so it cannot be instantiated outside
    private Singleton() {
    }

    // Provide a public static method to get the instance
    public static Singleton getInstance() {
        // Instantiate the singleton instance if null
        if (instance == null) {
            instance = new Singleton();
        }

        // return the singleton instance
        return instance;
    }
}
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs