C SC 225 Lecture 8: Design Patterns: Composite
[ previous
| schedule
| next ]
The Composite pattern
- Use this when primitive object needs to be grouped into composite which is itself treated like the primitive
- In other words, the composite has the same behavior as its parts
- The primitive object is called a leaf. Both the leaf and the composite
implement the same interface
- This is a Structural Pattern
- Some common examples are:
- Hierarchical GUI menus. Menu item can either be primitive or a submenu.
Submenu is composite that is treated like a primitive menu item
- Some Java GUI components are primitive (e.g. JButton), other components are
also containers (e.g. JPanel). Containers are like the submenus above.
- A given composite behavior (from interface) is implemented by having it invoke the same behavior on its primitives
and combining the results.
- Example is submenu that displays by having all its menu items display
- Example is container component that calculates its preferred size by getting the preferred sizes of
all its subcomponents
- Cost of composite object is sum of costs of its components. Sound like Decorator?
- Composite superficially resembles Decorator.
- Compare their class diagrams. See Horstmann pages 194 and 197.
- They differ in their intent. Decorator enhances its component, Composite merely groups its components
- Note the decorator wraps around a single "decoratee", while the composite wraps
around a collection of composites/primitives.
- Note the composite is really playing a dual role here, as both composite and primitive
- It may have behaviors that the leaf would not, like adding components
- A leaf may have behaviors that a composite would not, like getters
- If both implement a common interface, then both may have both sets of behaviors
- This is not an ideal situation; how to deal with it?
- Is there any way around it? Yes, but complicated.
[ C
SC 225 | Peter
Sanderson | Math Sciences server
| Math Sciences home page
| Otterbein ]
Last updated:
Peter Sanderson (PSanderson@otterbein.edu)