5

It seems like the builder pattern is good if you're making some linear chain of things (java's StringBuilder) or creating an object with many properties (PizzaBuilder).

Can it be extended to build a a tree without specifying possibly confusing node locations?

   a
 / | \
c  d  e
     / \
    f   g   

  TreeBuilder tb.addNode(levelNumber, parentNumber, nodeName) // I think this is terrible

  tb.addNode(2, 3, g)  //terrible

Or is just not a good idea with this pattern?

Thanks

marathon
  • 7,881
  • 17
  • 74
  • 137
  • 1
    StringBuilder doesn't follow the Builder pattern. The builder pattern "defines an instance for creating an object but letting subclasses decide which class to instantiate". – Jiahua Wang Feb 18 '12 at 03:04
  • 1
    By "builder," do you mean a so-called fluent builder class? If so, [this question](http://stackoverflow.com/questions/563328/elegant-and-maintainable-way-of-populating-tree-structures-in-c-sharp) addresses it somewhat. Of the group, I liked [this answer](http://stackoverflow.com/a/563380/1215441) best. – cutchin Feb 18 '12 at 04:41
  • @Jiahua - the quote that you provided is for Factory Method, not Builder (and is found on the inside cover of GoF). – kdgregory Feb 18 '12 at 13:17

2 Answers2

12

Yes, builder patterns can be used for trees. Each node in the tree needs its own builder instance.

Here's an example with a root and two child nodes.

Tree t = new TreeBuilder()
         .addNode(new TreeBuilder()
                  .addNode("foo")
                  .addNode("bar")
                  .toTree())
         .toTree()

https://sourceforge.net/p/practicalxml/code/HEAD/tree/trunk/src/main/java/net/sf/practicalxml/builder/ (the package.html contains example code).

haridsv
  • 9,065
  • 4
  • 62
  • 65
kdgregory
  • 38,754
  • 10
  • 77
  • 102
2

The Builder pattern is useful for when you have a class with a set of properties, and have predefined types of that class with various sets of properties.

You just want to make a tree:

a.add(c, d, e);
e.add(f, g);