Java Reference
In-Depth Information
Visitor
The Visitor pattern is often useful when operations must be performed over a large structure, and composite
results must be calculated. In this demonstration, the Visitor pattern is used to calculate the total cost for a project.
Four classes are used to represent project elements, and all of the classes implement a common interface,
ProjectItem . In this example, ProjectItem defines the accept method required to host a Visitor .
Example A.117 ProjectItem.java
1. import java.io.Serializable;
2. import java.util.ArrayList;
3. public interface ProjectItem extends Serializable{
4. public void accept(ProjectVisitor v);
5. public ArrayList getProjectItems();
6. }
The Project class represents the project itself, the Deliverable class a concrete product, the Task : a job of
some sort. In addition, there is a subclass of Task called DependentTask . This class holds a set of other Tasks
upon which it depends for its own completion.
Example A.118 Deliverable.java
1. import java.util.ArrayList;
2. public class Deliverable implements ProjectItem{
3. private String name;
4. private String description;
5. private Contact owner;
6. private double materialsCost;
7. private double productionCost;
8.
9. public Deliverable(){ }
10. public Deliverable(String newName, String newDescription,
11. Contact newOwner, double newMaterialsCost, double newProductionCost){
12. name = newName;
13. description = newDescription;
14. owner = newOwner;
15. materialsCost = newMaterialsCost;
16. productionCost = newProductionCost;
17. }
18.
19. public String getName(){ return name; }
20. public String getDescription(){ return description; }
21. public Contact getOwner(){ return owner; }
22. public double getMaterialsCost(){ return materialsCost; }
23. public double getProductionCost(){ return productionCost; }
24.
25. public void setMaterialsCost(double newCost){ materialsCost = newCost; }
26. public void setProductionCost(double newCost){ productionCost = newCost; }
27. public void setName(String newName){ name = newName; }
28. public void setDescription(String newDescription){ description = newDescription; }
29. public void setOwner(Contact newOwner){ owner = newOwner; }
30.
31. public void accept(ProjectVisitor v){
32. v.visitDeliverable(this);
33. }
34.
35. public ArrayList getProjectItems(){
36. return null;
37. }
38. }
Example A.119 DependentTask.java
1. import java.util.ArrayList;
2. public class DependentTask extends Task{
3. private ArrayList dependentTasks = new ArrayList();
4. private double dependencyWeightingFactor;
5.
6. public DependentTask(){ }
7. public DependentTask(String newName, Contact newOwner,
8. double newTimeRequired, double newWeightingFactor){
9. super(newName, newOwner, newTimeRequired);
10. dependencyWeightingFactor = newWeightingFactor;
11. }
 
Search WWH ::




Custom Search