DEV Community

Cover image for Singleton Pattern
eidher
eidher

Posted on • Edited on

1 1

Singleton Pattern

Ensure a class has only one instance and provide a global point of access to it.

Alt Text

Participants

  • Singleton: defines an Instance operation that lets clients access its unique instance. Instance is a class operation. Responsible for creating and maintaining its own unique instance.

Code

public class Main {

    public static void main(String[] args) {
        Singleton s1 = Singleton.instance();
        Singleton s2 = Singleton.instance();
        if (s1 == s2) {
            System.out.println("Objects are the same instance");
        }
    }
}

public class Singleton {
    private static Singleton instance;

    protected Singleton() {
    }

    public static Singleton instance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Objects are the same 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)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay