How should I approach wrapping the Composite pattern into the Builder pattern?

builder-pattern, composite, design-patterns, java, oop

Solution

In your builder, add methods "startComposite" and "endComposite". These methods push a composite onto a stack and remove a composite from the stack. Messages to add elements always add to the top of stack.

    builder.startComposite();
        builder.simpleElement1();
        builder.simpleElement2();
    builder.endComposite();
    builder.startComposite();
        builder.simpleElement2();
    builder.endComposite();

If your builder methods always return the builder, you can eliminate the repetition of the receiver:

    builder.
        startComposite().
            simpleElement1().
            simpleElement2().
        endComposite().
        startComposite().
            simpleElement2().
        endComposite();

Problem

Lets say that I have a Composite set up as follows: ``` public abstract class Element { //position, size, etc. //element methods //setters/getters } public class SimpleElement1 extends Element { //... } public class SimpleElement2 extends Element { //... } public class CompositeElement extends Element { protected List<Element> childrenElements; //methods to add/remove/get children } ``` Now, how would I go about wrapping this Composite up into a Builder pattern, so that I can simplify client code by enabling it not to care (or care less) about the intricacies of how to link children to their Composite?

Original source