luke1985
luke1985

Reputation: 2354

Composite design pattern parenting components

I've found that having composite pattern there is one thing that can be solved different ways: the parenting to the other composite.

What I mean is that if the "child" element should know about the "parent" element this can be done in two ways :

Now, my problem is which method to use? Which one is more reliable, more flexible and less error prone? Is there anybody who experienced both and decided to choose one of this methods?

Upvotes: 4

Views: 2922

Answers (1)

henginy
henginy

Reputation: 2061

Quoting wikipedia:

Composite pattern can be used when clients should ignore the difference between compositions of objects and individual objects.

Since the idea is to treat a group of objects as a single one (of the same type), usually the composite object iterates through its group (of children) in order to propagate the same behavior. Keeping a list of children in the parent makes more sense from this aspect.

Update: I misunderstood your question. Let me try again: Usually the composite object keeps reference to its children, for the reason above. The parent link might (or not) be excess. Why do you want to keep a reference to the parent? Is there a shared state between the children?

Update 2: Allright, the parent link should be there. In this case, both ways you mention are functionally equivalent and this is essentially an API design question. A TDD-ish way of thinking could help you here. For example, since the scenegraph is essentially a tree, a simple scenario can be creating the first nodes. This is how you'd do it in both versions (as I understand):

// First way:
// Shorter but still readable. Parent relationship established at construction, so you can count on that the parent property is always at its final state.
Composite root = new Composite(null);
Composite child = new Composite(root);

// Second way:
// Has an extra statement but more explicit. Also slightly more flexible since the parent relationship can be established _after_ construction. 
Composite root = new Composite();
Composite child = new Composite();
root.addChild(child);

Maybe re-parenting a node might be another interesting test, if you have that kind of a requirement. Determining your most important operations and designing for them will shape the API in the most appropriate way.

Upvotes: 1

Related Questions