Reputation: 2254
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
Reputation: 59
I believe enums are the best way to create singletons. If you are looking for downsides
Upvotes: 1
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