Java Reference
In-Depth Information
Chapter 5. Composite
A
composite
is a group of objects in which some objects may contain others; thus, one object
may represent groups, and another may represent an individual item, or
leaf
. When you model
a composite, two powerful concepts emerge. One important modeling idea is to design groups
so that they can contain either individual items or other groups. (A common error is to define
groups so that they can contain only leaves.) A second powerful concept is to define common
behaviors for individual objects and for compositions. You can bring these ideas together by
defining a common type for groups and items and by modeling groups as containing
a collection of objects of this type. This fulfills the intent of the C
OMPOSITE
pattern:
C
OMPOSITE
lets clients treat individual objects and compositions of objects uniformly.
An Ordinary Composite
Figure 5.1 shows an ordinary composite structure. The
Leaf
and
Composite
classes share
a common interface that
Component
abstracts, and a
Composite
object retains a collection
of other
Composite
and
Leaf
objects. Note that the
Component
class in Figure 5.1 is
an abstract class with no concrete operations, so you could define it as an interface that
Leaf
and
Composite
implement.
Figure 5.1. The key ideas of Composite are that composites can contain other
composites—not just leaves—and that composite and leaf nodes share a common
interface.
CHALLENGE 5.1
Give two reasons why the interface that
Leaf
and
Composite
share usually
appears in an abstract class rather than in an interface.