Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 950
Nebojša Avatar asked May 03 '12 18:05

Nebojša


People also ask

What is the difference between Builder design pattern and composite design pattern?

Composite creates Parent - Child relations between your objects while Builder is used to create group of objects of predefined types.

What are the issues to consider when implementing the composite pattern?

There are many issues to consider when implementing the Composite pattern: Explicit parent references. Maintaining references from child components to their parent can simplify the traversal and management of a composite structure. The parent reference simplifies moving up the structure and deleting a component.

When would it be appropriate to use the composite design pattern?

Composite pattern is used where we need to treat a group of objects in similar way as a single object. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy.


1 Answers

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();
like image 143
David Buck Avatar answered Sep 20 '22 00:09

David Buck