Java Reference
In-Depth Information
Example
Note:
For a full working example of this code example, with additional supporting classes and/or a RunPattern class,
see “ Composite on page 453 of the “ Full Code Examples ” appendix.
The Composite class diagram for the code example is shown in Figure 3.5 .
Figure 3.5. Composite class diagram for the code example
The example demonstrates how to use the Composite pattern to calculate the time required to complete a project
or some part of a project. The example has four principal parts:
Deliverable - A class that represents an end product of a completed Task .
Project - The class used as the root of the composite, representing the entire project.
ProjectItem - This interface describes functionality common to all items that can be part of a project. The
getTimeRequired method is defined in this interface.
Task - A class that represents a collection of actions to perform. The task has a collection of ProjectItem
objects.
The general functionality available to every object that can be part of a project is defined in the ProjectItem
interface. In this example, there is only a single method defined: getTimeRequired .
Example 3.9 ProjectItem.java
1. import java.io.Serializable;
2. public interface ProjectItem extends Serializable{
3. public double getTimeRequired();
4. }
Since the project items can be organized into a tree structure, two kinds of classes are ProjectItems . The
Deliverable class represents a terminal node, which cannot reference other project items.
Example 3.10 Deliverable.java
1. import java.io.Serializable;
2. public interface ProjectItem extends Serializable{
3. public double getTimeRequired();
4. }
The Project and Task classes are nonterminal or branch nodes. Both classes keep a collection of ProjectItems
that represent children: associated tasks or deliverables.
 
Search WWH ::




Custom Search