It's ugly, but most solutions to non-trivial extensions of the problem are just going to move the ugliness around.
For instance, you could encapsulate the three different behaviors in three different implementations of some interface, and then pass a different behavior implementation to the constructor of each enum. (This is basically the command or strategy approach that others are suggesting).
If you make these implementations, and the interface, separate classes, then you've potentially exposed that behavior beyond the enum, which is unnecessary and arguably ugly.
If you make them private static inner classes of the enum, you've moved the ugliness from the top of the file to the bottom of the file. How much less ugly this is is in the eye of the beholder.
public enum Foo {
ONE(new OneDelegate()),
TWO(new TwoDelegate()),
THREE(new ThreeDelegate());
// ////////////////////
// Private stuff
private final FooDelegate delegate;
private Foo(FooDelegate delegate) {
this.delegate = delegate;
}
// ////////////////////
// Public methods
public String doStuff(String stuff) {
return delegate.doStuff(stuff);
}
// ////////////////////
// Helper classes
private static interface FooDelegate {
String doStuff(String stuff);
}
private static class OneDelegate implements FooDelegate {
@Override
public String doStuff(String stuff) {
return "One " + stuff;
}
}
private static class TwoDelegate implements FooDelegate {
@Override
public String doStuff(String stuff) {
return "Two " + stuff;
}
}
private static class ThreeDelegate implements FooDelegate {
@Override
public String doStuff(String stuff) {
return "Three " + stuff;
}
}
}
The other obvious solution is to put all three behaviors in as private methods, and put a switch(this)
in the public method. Personally, I think this is ugly as sin, but a lot of ex-C programmers seem to like it. :)
public enum Foo {
ONE, TWO, THREE;
// ////////////////////
// Public methods
public String doStuff(String stuff) {
switch(this) {
case ONE:
return doStuffOne(stuff);
case TWO:
return doStuffTwo(stuff);
case THREE:
return doStuffThree(stuff);
default:
throw new IllegalStateException("Who am I?");
}
}
// ////////////////////
// Static helpers
private static String doStuffOne(String stuff) {
return "One " + stuff;
}
private static String doStuffTwo(String stuff) {
return "Two " + stuff;
}
private static String doStuffThree(String stuff) {
return "Three " + stuff;
}
}