Sobes.tech
Junior — Middle

Kuidas rakendada Singleton mustrit Java keeles?

sobes.tech AI

Vastus AI-lt

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

In Java, this can be implemented in several ways. One simple and thread-safe option is to use lazy initialization with the synchronized keyword or to use a static inner class.

Example using a static inner class:

public class Singleton {
    private Singleton() {
        // private constructor
    }

    private static class Holder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return Holder.INSTANCE;
    }
}

This approach guarantees that the instance is created only upon the first call to getInstance(), and it is thread-safe without using synchronized.