DEV Community

Cover image for Singleton Pattern

Singleton Pattern

eidher profile image eidher ・1 min read

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

Alt Text


  • 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.


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


Objects are the same instance
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Editor guide