Item 3 of Josh Block’s Effective Java (Enforce the Singleton Property With a Private Constructor or an Enumerator) mentions that “While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.”
Example:
public enum Elvis {
INSTANCE;
private final String[] favoriteSongs =
{ "Hound Dog", "Heartbreak Hotel" };
public void printFavorites() {
System.out.println(Arrays.toString(favoriteSongs));
}
}
Continued: “This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks.”
The biggest negative I see is: aren’t enums not supposed to have mutable state? It seems common to use a Singleton with state.
So has this pattern actually become more common since the publication date (2nd Edition published 2008)?
While enums aren’t generally given mutable state, this fact is based on assumptions of how an enum is going to be used. While these assumptions usually hold, they don’t always, and one such case where they do not is in the creation of a Singleton.
While it’s not the most common use of enums, it’s perfectly legitimate to have an enum with a mutable state, though you may want to indicate this fact in your code so any other programmer who might be looking at it don’t get confused.
As for a popularity of this design pattern, I’ve seen it fairly often, but not so much that I’d say it has become “common.”