Last active
December 11, 2015 12:58
-
-
Save eneveu/4604088 to your computer and use it in GitHub Desktop.
DSL to build a tree or "hierarchy" in a visually elegant way --> when you want the hierarchy to be easily readable in the source file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package rubber.duck; | |
import com.google.common.collect.ImmutableMultimap; | |
import com.google.common.collect.Lists; | |
import org.apache.commons.lang.NotImplementedException; | |
import java.util.List; | |
// TODO: generate the tree from the list of temporary element holders | |
// fail fast if an user calls methods in the wrong order | |
public class TreeBuilder<T> { | |
private final List<TemporaryElementHolder<T>> temporaryElementHolders = Lists.newArrayList(); | |
public TreeBuilder<T> ____(T element) { | |
return addElementAtLevel(element, 1); | |
} | |
public TreeBuilder<T> ________(T element) { | |
return addElementAtLevel(element, 2); | |
} | |
public TreeBuilder<T> ____________(T element) { | |
return addElementAtLevel(element, 3); | |
} | |
public TreeBuilder<T> ________________(T element) { | |
return addElementAtLevel(element, 4); | |
} | |
public TreeBuilder<T> ____________________(T element) { | |
return addElementAtLevel(element, 5); | |
} | |
/** | |
* Use this method when your tree is too deep to use the "____" methods. | |
*/ | |
public TreeBuilder<T> addElementAtLevel(T element, int level) { | |
temporaryElementHolders.add(new TemporaryElementHolder<T>(element, level)); | |
return this; | |
} | |
public ImmutableMultimap<T, T> build() { | |
throw new NotImplementedException("TODO"); | |
} | |
private static class TemporaryElementHolder<T> { | |
final T element; | |
final int level; | |
private TemporaryElementHolder(T element, int level) { | |
this.element = element; | |
this.level = level; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package rubber.duck; | |
import com.google.common.collect.ImmutableMultimap; | |
public class TreeBuilderDemo { | |
public void demo() { | |
ImmutableMultimap<String, String> tree = new TreeBuilder<String>() | |
.____("a") | |
.________("b") | |
.____________("c") | |
.____________("d") | |
.________________("e") | |
.____________("f") | |
.________("g") | |
.____________("h") | |
.____("i") | |
.build(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment