Design Patterns: Composite

Posted by Monik, 27 October 2010.
Programming Code Design Design Patterns
Book summary
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.


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


Comments: