Java Reference
In-Depth Information
Consequences of Cycles
Most operations on a composite, such as counting its number of leaf nodes, make sense even
if the composite is not a tree. Usually, the only difference that nontree composites introduce is
that you have to be careful to not operate on a given node twice. However, some operations
become meaningless if the composite contains a cycle.
Operations that don't make sense if a composite contains cycles include any behavior that
depends on the length of a path in the composite. For example, the height of a tree is the
length of the longest path from the root to a leaf. This concept does not apply when cycles
appear in a composite, as there is no limit to the length of some paths. In the fireworks
process example, there is no "height" of the process composite. This mirrors the fact that there
is no limit to the number of times an aerial shell may be reworked.
Another result of allowing composites that are not trees is that you lose the ability to assume
that each node has a single parent. If a composite is not a tree, a node may have more than one
parent. For example, the process that Figure 5.8 models might have several composite steps
that use the inspect step, giving the inspect object multiple parents. There is no inherent
problem in a node's having multiple parents, but a problem may arise if you create a model
that insists otherwise.
Summary
C OMPOSITE contains two powerful, related concepts. One concept is that a group can contain
either individual items or other groups. Related to this concept is the idea that groups and
individual items may share a common interface. These ideas come together in object
modeling, whereby you can create an abstract class or a Java interface that defines
the behaviors that are common to groups and to individual objects.
Modeling composites often leads to recursive definition of methods on composite nodes.
When recursion is present, a danger exists of writing code that produces an infinite loop. To
avoid such problems, you can take steps to guarantee that your composites are always trees.
Alternatively, you can allow cycles to occur in a composite, but you have to modify your
algorithms to watch for recursion. You can handle cycles in composites by maintaining
a collection of observed nodes.
Search WWH ::




Custom Search