Enum Singleton

If you consider a singleton for solving a problem, you really should think again if it is the correct solution or if you are coding the equivalent of global variable. If you still want to use the singleton approach, ask your colleagues if this would be a good approach. If they agree, I might have a new idea for you.

The crucial part of a singleton implementation is to ensure that no one creates a second instance. The common approach is to use a private constructor. This works ok, but you still could call such a constructor if you are running privileged code. And the private constructor is kind of ugly since its only purpose is to prevent anybody from calling it. And if serialization is important for your app you have to take care of it manually. Joshua Bloch proposes in his book “Effective Java” to use a Enum for singleton implementations like this:

public enum Elvis {

INSTANCE;

public void leaveTheBuilding(){.}

}

Which is simple, easy and rock solid. You can’t break it as long as you don’t use byte code manipulation.

At first I was a little skeptical. Would readers of the piece of code understand its meaning and intent? After all enums are for collections of fixed objects, right? But by now I am convinced. Although it was completely new for me there is no problem in understanding it. The enum makes it obvious that there will be only one instance, and the name of the single instance makes it obvious what the intention is.

So my opinion on this is: Don’t use singletons! But if you have to, make it an enum.

Share:
  • DZone
  • Digg
  • del.icio.us
  • Reddit
  • Facebook
  • Twitter