Sobes.tech
Junior — Middle

How is the Singleton pattern implemented?

sobes.tech AI

Answer from AI

The Singleton pattern in Java is implemented to guarantee that only one instance of a class exists and to provide a global point of access to that instance. One common way is to use a private constructor and a static field to hold the single object, as well as a static method to get that object:

public class Singleton {
    private static Singleton instance;

    private Singleton() {
        // private constructor
    }

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

Here, synchronized ensures thread safety. You can also use lazy initialization with an inner static class or enum for a simpler and safer implementation.

How is the Singleton pattern implemented? — Java - sobes.tech