Skip to content

Instantly share code, notes, and snippets.

@eneveu
Created January 22, 2013 18:13
Show Gist options
  • Save eneveu/4596800 to your computer and use it in GitHub Desktop.
Save eneveu/4596800 to your computer and use it in GitHub Desktop.
DSL to build an enum hierarchy in a visually elegant way
package rubber.duck;
import com.google.common.collect.ImmutableSet;
public enum Foo implements FooHierarchy.Node {
ONE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN;
@Override
public FooHierarchy.Node withChildren(FooHierarchy.Node... children) {
return new FooHierarchy.NodeWithChildren(this, ImmutableSet.copyOf(children));
}
private static final FooHierarchy.Node hierarchy =
ONE.withChildren(
TWO.withChildren(
THREE,
FOUR.withChildren(
FIVE
)
),
SIX,
SEVEN
);
}
package rubber.duck;
import com.google.common.collect.ImmutableSet;
import javax.annotation.Nonnull;
public class FooHierarchy {
public interface Node {
Node withChildren(Node... children);
}
public static class NodeWithChildren implements Node {
@Nonnull
final Node element;
@Nonnull
final ImmutableSet<Node> children;
NodeWithChildren(@Nonnull Node element, @Nonnull ImmutableSet<Node> children) {
this.element = element;
this.children = children;
}
public Node withChildren(Node... children) {
throw new UnsupportedOperationException("Cannot add children to a node that already has children");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment