The Composite Pattern: Intent
The Composite Pattern: Intent
Composite
Pattern
l Intent
é Compose objects into tree structures to represent part-whole hierarchies.
Composite lets clients treat individual objects and compositions of objects
uniformly. This is called recursive composition.
l Motivation
1
The Composite Pattern
l Motivation
l Applicability
Use the Composite pattern when
é You want to represent part-whole hierarchies of objects
é You want clients to be able to ignore the difference between compositions
of objects and individual objects. Clients will treat all objects in the
composite structure uniformly.
Design Patterns In Java
The Composite Pattern Bob Tarr
3
l Structure
2
The Composite Pattern
l Consequences
é Benefits
Ý It makes it easy to add new kinds of components
Ý It makes clients simpler, since they do not have to know if they are dealing
with a leaf or a composite component
é Liabilities
Ý It makes it harder to restrict the type of components of a composite
l Implementation Issues
é A composite object knows its contained components, that is, its children.
Should components maintain a reference to their parent component?
Ý Depends on application, but having these references supports the Chain of
Responsibility pattern
é Where should the child management methods (add(), remove(), getChild())
be declared?
Ý In the Component class: Gives transparency, since all components can be
treated the same. But it's not safe, since clients can try to do meaningless
things to leaf components at run-time.
Ý In the Composite class: Gives safety, since any attempt to perform a child
operation on a leaf component will be caught at compile-time. But we lose
transparency, since now leaf and composite components have different
interfaces.
3
The Composite Pattern
Component
operation( ) children
add( )
remove( )
getChild( )
Leaf Composite
TRANSPARENT
Component children
operation( )
Composite
Leaf
add( )
remove( )
getChild(
SAFE
l Implementation Issues
é Should Component maintain the list of components that will be used by a
composite object? That is, should this list be an instance variable of
Component rather than Composite?
Ý Better to keep this part of Composite and avoid wasting the space in every leaf
object
é Is child ordering important?
Ý Depends on application
é Who should delete components?
Ý Not a problem in Java! The garbage collector will come to the rescue!
é What's the best data structure to store components?
Ý Depends on application
4
Composite Pattern Example 1
Button[] buttons;
Menu[] menus;
TextArea[] textAreas;
WidgetContainer[] containers;
5
Composite Pattern Example 1 (Continued)
Component components
6
Composite Pattern Example 1 (Continued)
7
Composite Pattern Example 3
Equipment equipment
Bus Chassis