« Writing a class hierarchy Comparator | Home | Making BSF and Rhino work »
Putting extra state on enum constants
I had occasion the other day to push some extra state onto my enum constants. I hadn’t done this before and it took me a while to find any good docs on it on the web.
In my case I had some classes in the Strategy pattern and I wanted to create an enumerated type for the different strategies. Instead of making a map of enum value to strategy instance, I just pushed the instances into the enum values themselves.
Here’s an example with some helpful comments:
Once you have defined this enumerated type, you can use the enumerated values as expected but you can call getStrategy() on them to retrieve the actual strategy instance.
I’m not sure this is a very compelling example of usage but it would be difficult to show enough code to explain why this was worthwhile in my case. The alternative here is of course to just say “new Person(new KungFuStrategy())” and skip the whole enumerated type entirely. In my case, I’m starting from an inherently string-based API and I want to start from the name of the enumerated type (and hide the name of the actual class related to the type). The built-in name() and valueOf() methods in enum make this easy.
One case where this is more obviously useful is if the enumerated values have some real constant attributes that correspond to each enumerated value. In that case, it’s a big win to create those directly on the enumerated type. Check out the Planet example in Sun’s docs on enums for a good use case on this.
Another interesting idea is that the state on the enum values does not have to be constant - each value is an instance that can have mutable state (via getter/setters). Seems like there would only be some rare cases where you’d want enumerated values with variable state but it’s an interesting idea. Something like:
This would let you store the price per size and change it dynamically as needed.
Gotta love that powerful little enum!
About this entry
You’re currently reading “Putting extra state on enum constants,” an entry on Pure Danger Tech
- Published:
- Jan 03 2007 / 9:36 am
- Category:
- programming, Java, jdk5
- Vote:
- Other posts with these tags:

2 Comments
Jump to comment form | comments rss | trackback uri