Java Reference
In-Depth Information
Composite
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 A.144 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 A.145 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.
Example A.146 Project.java
1. import java.util.ArrayList;
2. import java.util.Iterator;
3. public class Project implements ProjectItem{
4. private String name;
5. private String description;
6. private ArrayList projectItems = new ArrayList();
7.
8. public Project(){ }
9. public Project(String newName, String newDescription){
10. name = newName;
11. description = newDescription;
12. }
13.
14. public String getName(){ return name; }
15. public String getDescription(){ return description; }
16. public ArrayList getProjectItems(){ return projectItems; }
17. public double getTimeRequired(){
18. double totalTime = 0;
19. Iterator items = projectItems.iterator();
20. while(items.hasNext()){
21. ProjectItem item = (ProjectItem)items.next();
22. totalTime += item.getTimeRequired();
23. }
24. return totalTime;
25. }
26.
27. public void setName(String newName){ name = newName; }
28. public void setDescription(String newDescription){ description = newDescription; }
29.
30. public void addProjectItem(ProjectItem element){
31. if (!projectItems.contains(element)){
32. projectItems.add(element);
 
Search WWH ::




Custom Search