Sobes.tech
Junior — Middle

How to implement the Singleton pattern in Java?

sobes.tech AI

Answer from AI

The Singleton pattern guarantees that a class has only one instance and provides a global point of access to it.

In Java, it can be implemented as follows:

public class Singleton {
    private static Singleton instance;

    private Singleton() {
        // private constructor prevents instantiation from outside
    }

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Here, the getInstance() method creates the object on the first call and returns it on subsequent calls, ensuring the uniqueness of the instance.

How to implement the Singleton pattern in Java… - sobes.tech