All right, so I've explored the Groovy builders. It is a pretty powerful feature, especially for EAI (enterprise application integration) in the sense that it allows us to "configure" systems using domain specific languages. The builder can be implemented in Groovy but I chose to do it in Java:
public class MyBuilder extends BuilderSupport {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
@Override
protected void setParent(Object parent, Object child) {
System.out.println("setParent:"+parent+" "+child);
if (parent instanceof Node)
{
((Node) parent).children.add((Node) child);
}
}
@Override
protected Object createNode(Object name) {
return createNode(name, null, null);
}
@Override
protected Object createNode(Object name, Object value) {
return createNode(name, null, value);
}
@Override
protected Object createNode(Object name, Map attr) {
return createNode(name, attr, null);
}
@Override
protected Object createNode(Object name, Map attr, Object value) {
System.out.println("Creating node:"+name);
Node n=new Node();
n.name=(String) name;
n.attributes=attr;
n.value=(String) value;
return n;
}
}
Node is implemented as follows:
public class Node {
public String value;
public ArrayList children=new ArrayList();
public String name;
public Map attributes;
public String toString() {
StringBuffer buf=new StringBuffer();
buf.append("Node name="+name+" attributes="+attributes+"value="+value+"\n");
buf.append("{\n");
buf.append("\t"+children.toString()+"\n");
buf.append("}\n");
return buf.toString();
}
}
And here is an example Groovy script:
def builder=new MyBuilder()
def root=builder.foo(x:1, y:2) {
child1("goo")
child2(z:5, x:0021, u:123) {
subChild3("goo")
}
}
println root