Summary on basis of the book ,,Design Patterns: Elements of Reusable Object-Oriented Software'', by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Addison-Wesley, 1995.
We compose objects to tree structures - when we want to treat individual objects and compositions of objects in the same way.
It's recursive composition.
The clients do not distinguish between invidual subclasses, they treat all of them uniformly.
Should the methods be declared in superclass or subclasses? Depends if you favor safety (subclasses) or transparency (superclass):
class Node{
Node[] children;
getChildAt(int idx);
...
}
class FullNode extends Node{
}
class LeafNode extends Node{
}
We compose objects to tree structures - when we want to treat individual objects and compositions of objects in the same way.
It's recursive composition.
The clients do not distinguish between invidual subclasses, they treat all of them uniformly.
Should the methods be declared in superclass or subclasses? Depends if you favor safety (subclasses) or transparency (superclass):
- if you favor safety, you can still add a getComposite() method to the superclass, and leaves would just return null:)
- in case you favor transparency remember to throw at least exceptions in leaf subclasses, so that a possible bug will be noticed
Comments
Want to leave a comment? Visit this post's issue page
on GitHub and just post your comment as the issue's comment (you'll need a GitHub account. What? Like you don't have one yet?!).
Comments: