Java Reference
In-Depth Information
The MachineComponent code delegates an isTree() call to its abstract
isTree(s:Set) method:
public boolean isTree()
{
return isTree(new HashSet());
}
public abstract boolean isTree(Set s);
The implementation of isTree() for Machine reflects the fact that individual machines are
always trees:
protected boolean isTree(Set visited)
{
visited.add(this);
return true;
}
The MachineComposite implementation of isTree() should add the receiving object
( this ) to the visited set and then iterate over the composite's components. The method can
return false if any component has been previously visited or if any component is not itself a
tree. Otherwise, the method can return true .
CHALLENGE 5.5
Write the code for MachineComposite.isTree(Set s) .
With some care, you can guarantee that an object model is a tree by refusing changes that
would make isTree() false. On the other hand, you may need to allow composites that are
not trees, particularly when the problem domain that you are modeling contains cycles.
Composites with Cycles
The nontree composite that Challenge 5.4 refers to was an accident. For physical objects, you
may want to disallow the notion that an object is contained by more than one other object.
Physical objects also usually cannot appear in cyclic models, in which an object ultimately
contains itself. However, a problem domain can have nonphysical elements where cycles of
containment make sense. This occurs frequently when modeling process flows.
Consider the construction of aerial shells such as the one that Figure 5.6 depicts. We launch
a shell from a mortar by igniting the lifting charge of black powder that is seated beneath
the core charge. The secondary fuses burn while the shell in the air, eventually reaching the
core. When the shell core explodes its stars ignite, creating the visual effects of aerial
fireworks.
Search WWH ::




Custom Search