Java Reference
In-Depth Information
The Composite pattern supports these characteristics by defining a class structure that supports extensibility. This
structure is composed of a component, leaf, and Composite class.
The base component provides the core model, defining standard methods or variables to be used by all the objects
in the Composite.
Leaf classes support terminal behavior. That is, they represent parts of the Composite, but they cannot contain
other components.
Composite or branch classes can have other components added to them, permitting extensibility of the Composite
structure.
A drawing created using graphical editing tools is a common example of the Composite pattern in action. With a
drawing, a number of elementary shapes can be associated and treated as a whole; you also can define drawings
so that they contain other drawings, or a mixture of drawings and shapes.
Additional possibilities for Composite pattern use include applications with organizational charts, task
breakdowns, schedules, and outlining features. Applications that support grouping are also good candidates for
the Composite pattern, provided that the grouping action can be performed recursively and that the final product,
as well as its component elements, have the same functional behavior.
Implementation
Figure 3.4. Composite class diagram
The Composite has three elements:
Component -
The
Component
interface defines methods available for all parts of the tree structure.
Component
may be implemented as abstract class when you need to provide standard behavior to all of the sub-types.
Normally, the component is not instantiable; its subclasses or implementing classes, also called nodes, are
instantiable and are used to create a collection or tree structure.
Composite -
This class is defined by the components it contains; it is composed by its components. The
Composite
supports a dynamic group of
Components
so it has methods to add and remove
Component
instances
from its collection. The methods defined in the
Component
are implemented to execute the behavior specific for
this type of
Composite
and to call the same method on each of its nodes. These
Composite
classes are also called
branch or container classes.
Leaf -
The class that implements the
Component
interface and that provides an implementation for each of the
Component
's methods. The distinction between a
Leaf
class and a
Composite
class is that the
Leaf
contains no
references to other
Components
. The
Leaf
classes represent the lowest levels of the containment structure.