문제

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

도움이 되었습니까?

해결책

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);

다른 팁

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).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top