Implementing Singleton Alternatively

The standard method of implementing singleton design pattern is this:

public class Singleton {
    private static Singleton instance = new Singleton();

    public static Singleton getInstance() {
        return instance;
    }

    private Singleton() {}
}

I was wondering if you could also implement it like this:

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

and if yes which version is better?

Answer

Neither. In both cases, a trusted consumer can invoke the private constructor via reflection. An additional problem is that it these implementation don’t play nicely with serialization unless you take extra steps to make it so (by default, if you take the naïve approach, every time a Singleton is deserialized, it will create a new instance).

The correct solution is to use an enum that defines a single value.

public enum Singleton {
    INSTANCE;

    // methods
}

From Effective Java:

While this approach is yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Leave a Reply

Your email address will not be published. Required fields are marked *