Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a clean way to use the Builder pattern to build a multi-level tree?

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

like image 773
marathon Avatar asked Feb 18 '12 02:02

marathon


People also ask

What are the consequences of applying the builder design pattern?

Here are key consequences of the Builder pattern: It lets you vary a product's internal representation. The Builder object provides the director with an abstract interface for constructing the product. The interface lets the builder hide the representation and internal structure of the product.

When should builder pattern be used?

Builder pattern aims to “Separate the construction of a complex object from its representation so that the same construction process can create different representations.” It is used to construct a complex object step by step and the final step will return the object.

Is builder pattern thread safe?

Last, but not least, builders are not thread-safe. While immutable objects can be freely shared between threads, builders cannot because of the mutable state.

What is the real life use case of the builder design pattern?

In the Real World The simplest real world example of the builder pattern, which most of us are familiar with, is when we make (or order) a pizza. The pizza toppings cannot be added in any random order or the whole thing is likely to come out a mess. Instead, there is a step-by-step process that is followed.


2 Answers

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

like image 109
kdgregory Avatar answered Oct 17 '22 11:10

kdgregory


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);
like image 38
Jiahua Wang Avatar answered Oct 17 '22 12:10

Jiahua Wang