Composite - Structural
Pattern
Intent
-
Composite objects into tree structures to represent
part-whole hierarchies.
-
Clients treat individual objects (leaves in the trees)
and compositions of objects (nodes in the tree) uniformly
Motivation
-
Simple components are grouped into larger components,
hence the need to distinguish between primitive and container objects.
-
Describes how to use recursive composition so as
to make primitive and container objects similar to the client.
-
Abstract class represents both primitives and their
containers.
-
Defines virtual methods that the primitives and containers
implement.
-
In addition to the basic set of methods that the
primitives implement, the containers also implement methods for accessing
and managing its children which can be either containers or primitives.
Structure
Clients use the Component class interface to interact
with objects in the composite structure. If the recipient is a Leaf, then
the request is handled directly. If the recipient is a Composite, then
it usually forwards requests to its child components.
Example
Implementation
-
Explicit parent references
-
Sharing components - difficult when a component has
more than one parent
-
Maximising component interface - primitive and composite
classes transparent to client
-
Declaring child management operations - trade-off
between safety and transparency, emphasis is on transparency over safety
-
Component implement a list of components? - child
pointer in Component class, space penalty for every leaf, only useful if
there are very few children
-
Child Ordering - use of iterators or traversers (as
in Performer).
-
Caching for better performance - caching of traversal
and search info of children (Bounding Box)
-
Composite responsible for deleting its children.
Use in Graphics Related Problems
-
To build a class framework for scene-graph hierarchy.
-
Example, In a scene, there can be a Component Class
can be Node, the leaves of the scene are the basic geometry, the Composite
Class can be a Group. The Group contains methods for accessing its children/parent.
Classes like Switch, LOD can be derived from Group. This structure can
be seen in Performer.