I have often read/heard that the composite pattern is a good solution to represent hierarchical data structures like binary trees, which it is great to explain this pattern because internal nodes are composite
objects and leaves are leaf
objects. I can appreciate that using this pattern, it is easy to visit every element in an uniform way.
However, I am not so sure if it is the best example if you are considering that a tree is filling on demand (every time an insert
method is executed) because we have to convert a leaf
to composite
object many times (e.g. when leaf
has to add a child). To convert a leaf
object, I imagine a tricky way like (inspired by become:
from Smalltalk I guess):
aComposite = aLeaf.becomeComposite();
aComposite.addChild(newElement);
//destroy aLeaf (bad time performance)
To sum up, Is a good example the use of a tree-like structure to illustrate the composite pattern if this kind of structure is born commonly empty and then you have to add/insert elements?
Aucun commentaire:
Enregistrer un commentaire