Composite
Intent
Compose
objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual
objects and compositions of objects uniformly.
-Design Patterns, GoF
The
other day I was listening to NPR’s Car Talk, a popular weekly broadcast during
which callers ask questions about their vehicles. Before every program break, the show’s hosts
ask callers to dial 1-800-CAR-TALK, which corresponds to 1-800-227-8255. Of course, the former proves much easier to
remember than the latter, in part because the words “CAR TALK” are composite:
two words that represent seven digits.
Humans generally find it easier to deal with composites, rather than
their individual components. Likewise,
when you develop object-oriented software, it’s often convenient to manipulate
composites just like you manipulate individual components.
-David Geary, Javaworld.com
Questions
1)
Is it possible to restrict the components of a composite?
2)
Can a component have multiple parents?
3)
Does a component have a reference to its parent?
4)
Where should the child management methods (i.e. add and remove) be
declared? In the
composite or in the component?
What are the advantages of each?
5)
Under what circumstances does the Composite pattern violate standard OO design
principles?
Examples – Which are Composites?
1) Java
Swing Component
2)
Apache Struts Tiles
3)
Caching
Implement It!
Imagine
you are creating a feature for HR to calculate employee salary. There are two main types of employees:
managers and workers. The salary for
each employee is the sum of the individual’s salary plus everyone underneath
her. How could this be implemented using
the composite pattern.
References
·
A
Look at the Composite Design Pattern, David Geary (Javaworld.com, September 2003)