开发者

Groovy Builder support

Ho开发者_如何学Cw can i build the above pattern using groovy builder support

emp = empFileFactory.root()
{
  emp(id: '3', value: '1')

  emp(id:'24')
  {
    emp(id: '1', value: '2')
    emp(id: '6', value: '7')
    emp(id: '7', value: '1')
  }

  emp(id: '25')
  {
    emp(id: '1', value: '1')
    emp(id: '6', value: '7')
  }

}

i'm trying to build the above strucutre in groovy can some one explain how could i acieve this


You can do something like this (this has no error handling, and just returns null for methods that I don't expect to be called):

// First define our class to hold our created 'Emp' objects
@groovy.transform.Canonical
class Emp {
  String id
  String value
  List<Emp> children = []
}

class EmpBuilder extends BuilderSupport{
  def children = []
  protected void setParent(Object parent, Object child){
    parent.children << child
  }
  protected Object createNode(Object name){
    if( name == 'root' ) {
      this
    }
    else {
      null
    }
  }
  protected Object createNode(Object name, Object value){
    null
  }
  protected Object createNode(Object name, Map attributes){
    if( name == 'emp' ) {
      new Emp( attributes )
    }
    else {
      null
    }
  }
  protected Object createNode(Object name, Map attributes, Object value){
    null
  }
  protected void nodeCompleted(Object parent, Object node) {
  }
  Iterator iterator() { children.iterator() }
}

Then, if we call this with your required builder code like so:

b = new EmpBuilder().root() {
  emp(id: '3', value: '1')

  emp(id:'24') {
    emp(id: '1', value: '2')
    emp(id: '6', value: '7')
    emp(id: '7', value: '1')
  }

  emp(id: '25') {
    emp(id: '1', value: '1')
    emp(id: '6', value: '7')
  }
}

We can print out the 'tree' like so

b.each { println it }

and see we get the structure we asked for:

Emp(3, 1, [])
Emp(24, null, [Emp(1, 2, []), Emp(6, 7, []), Emp(7, 1, [])])
Emp(25, null, [Emp(1, 1, []), Emp(6, 7, [])])


You want to implement extend the BuilderSupport class, which is pretty easy to do. There's a pretty nice tutorial here.

You need to implement a few methods, but the naming should be pretty self-explanatory:

  • createNode creates a node (each node has a name and optional attributes and/or a value)
  • setParent assigns a node as another nodes parent

That's pretty much it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜