Other Ways of Singleton in Java [duplicate]

No, it is not. You didn’t declare myClass private static final, nor the getInstance() is static. The code also doesn’t really compile.

Here’s the Singleton idiom:

public class MyClass {
    private static final MyClass myClass = new MyClass();

    private MyClass() {}

    public static MyClass getInstance() {
        return myClass; 
    }
}

It should be private, so that nobody else can access it directly. It should be static so that there’s only one of it. It should be final so that it cannot be reassigned. You also need to instantiate it directly during declaration so that you don’t need to worry (that much) about threading.

If the loading is expensive and you thus rather prefer lazy loading of the Singleton, then consider the Singleton holder idiom which does initialization on demand instead of during classloading:

public class MyClass {
    private MyClass() {}

    private static class LazyHolder {
        private static final MyClass myClass = new MyClass();
    }

    public static MyClass getInstance() {
        return LazyHolder.myClass;
    }
}

You should however put big question marks whether you need a Singleton or not. Often it’s not needed. Just a static variable, an enum, a factory class and/or dependency injection is often the better choice.

Leave a Comment