Is there a clean way to use the Builder pattern to build a layered tree?

The builder pattern seems to be good if you create a linear chain of things (java StringBuilder) or create an object with many properties (PizzaBuilder).

Is it possible to expand it to build a tree without specifying confusing node locations?

a / | \ cde / \ fg TreeBuilder tb.addNode(levelNumber, parentNumber, nodeName) // I think this is terrible tb.addNode(2, 3, g) //terrible 

Or is it not a good idea with this template?

thanks

+4
source share
2 answers

The Builder pattern is useful when you have a class with a set of properties and has predefined types of this class with different sets of properties.

You just want to create a tree:

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

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

Here is an example with a root and two child nodes.

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

And here is a real world example used to build XML: http://practicalxml.svn.sourceforge.net/viewvc/practicalxml/trunk/src/main/java/net/sf/practicalxml/builder/ (package.html contains sample code )

+8
source

Source: https://habr.com/ru/post/1397147/


All Articles