Singleton Pattern

Problem

Exactly one instance of a class is allowed - it is a "singleton." Objects need a global and single point of access.

Solution

Define a static method of the class that returns the singleton.

public class SingletonDemo {

    private static SingletonDemo instance = null;
    private SingletonDemo() { }

    public static synchronized SingletonDemo getInstance() {

        if (instance == null) {
            instance = new SingletonDemo();
        }

        return instance;
    }

}

This is a lazy initialization.

Last updated