Rasika Perera Govinnage
Rasika Perera Govinnage

Reputation: 2254

advantage of enum over class in singleton pattern

I recently came to know that enum is a more effcient way to implement singleton.

Singleton with enum:

public enum Singleton{
INSTANCE;
    public void doStuff(){
        //......
    }
    public void doMoreStuff(){
        //......
    }
}

Singleton with class:

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

    private Singleton(){}

    public static Singleton getInstance(){
        return INSTANCE;
    }

    public void doStuff(){
        //......
    }
    public void doMoreStuff(){
        //......
    }
}

QUESTION: What are the possible advantages or disadvantages of using enum over class to implement the singleton ?

Upvotes: 2

Views: 1234

Answers (2)

venkatesh
venkatesh

Reputation: 59

I believe enums are the best way to create singletons. If you are looking for downsides

  1. It is not possible to have lazy load with enums
  2. If you serialize and deserialize the enum, the members in the enums are reset to default value.
  3. If you change your mind and want to make it non-singleton, It is easy with double checked synchronized singleton.

Upvotes: 1

Duncan Jones
Duncan Jones

Reputation: 69339

As explained by Joshua Bloch, the two approaches are functionally identical if your singleton is not serializable. Although you may wish to add code to your private Singleton constructor to prevent reflection being used to create a second instance.

If your singleton is serializable, then the enum approach will provide all the necessary plumbing for free, whereas with the static field approach, you have to add that yourself.

In my view, there is no downside to adopting the enum approach.

Upvotes: 2

Related Questions