DEV Community

Cover image for Singleton Pattern
eidher
eidher

Posted on • Updated on

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

Top comments (0)