Java Reference
In-Depth Information
Composite (Chapter 5)
SOLUTION 5.1
One answer is that
Design Patterns
(Gamma et al. 1995) shows
Component
as an abstract
class, so Java developers may implement it that way without considering the use of a Java
interface. Another answer is that the
Component
superclass often has fields and methods that
its subclasses can share. For example, the
Component
class may have a
name
instance
variable and a concrete
toString()
method that uses it.
SOLUTION 5.2
For the
Machine
class,
getMachineCount()
should be something like:
public int getMachineCount()
{
return 1;
}
The class diagram shows that
MachineComposite
uses a
List
object to track its
components. To count the machines in a composite, you might write:
public int getMachineCount()
{
int count = 0;
Iterator i = components.iterator();
while (i.hasNext())
{
MachineComponent mc = (MachineComponent) i.next();
count += mc.getMachineCount();
}
return count;
}
SOLUTION 5.3
Method Class Definition
getMachineCount()
MachineComposite
Return the sum of the counts for each
component in
components
.
Machine
Return 1.
isCompletelyUp()
MachineComposite
Return if all components are "completely up."
Machine
Return
true
if this machine is up.
stopAll()
MachineComposite
Tell all components to "stop all."
Machine
Stop this machine.
getOwners()
MachineComposite
Create a set, not a list, add the owners of all
components, and return the set.
Return this machine's owners.
Machine
getMaterial()
MachineComposite
Return a collection of all the material on
components.
Machine
Return the material that is on this machine.