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?
Composite creates Parent - Child relations between your objects while Builder is used to create group of objects of predefined types.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With