Today I was browsing through some questions on this site and I found a mention of an enum
being used in singleton pattern about purported thread safety benefits to such solution.
I have never used enum
s and I have been programing in Java for more than couple a years now. And apparently they changed a lot. Now they even do full blown support of OOP within themselves.
Enum
s enumerate a fixed set of values, in a self-documenting way.They make your code more explicit, and also less error-prone.
Why not using
String
, orint
, instead ofEnum
, for constants?if
) to assure your argument is in the valid range.String
s, anyway (this depends on the complexity of theEnum
).Moreover, each of the
Enum
's instances is a class, for which you can define its individual behaviour.Plus, they assure thread safety upon creation of the instances (when the enum is loaded), which has seen great application in simplifying the Singleton Pattern.
This blog illustrates some of its applications, such as a State Machine for a parser.
enum
means enumeration i.e. mention (a number of things) one by one.OR
For example:
Advantages of enum:
for more
What gave me the Ah-Ha moment was this realization: that Enum has a private constructor only accessible via the public enumeration:
There are many answers here, just want to point two specific ones:
1) Using as constants in
Switch-case
statement. Switch case won't allow you to use String objects for case. Enums come in handy. More: http://www.javabeat.net/2009/02/how-to-use-enum-in-switch/2) Implementing
Singleton Design Pattern
- Enum again, comes to rescue. Usage, here: What is the best approach for using an Enum as a singleton in Java?You can use an Enum to represent a smallish fixed set of constants or an internal class mode while increasing readability. Also, Enums can enforce a certain rigidity when used in method parameters. They offer the interesting possibility of passing information to a constructor like in the Planets example on Oracle's site and, as you've discovered, also allow a simple way to create a singleton pattern.
ex:
Locale.setDefault(Locale.US)
reads better thanLocale.setDefault(1)
and enforces the use of the fixed set of values shown in an IDE when you add the.
separator instead of all integers.