Java Reference
In-Depth Information
19. public double getTimeRequired(){ return timeRequired; }
20.
21. public void setName(String newName){ name = newName; }
22. public void setOwner(Contact newOwner){ owner = newOwner; }
23. public void setTimeRequired(double newTimeRequired){ timeRequired =
newTimeRequired; }
24.
25. public void addProjectItem(ProjectItem element){
26. if (!projectItems.contains(element)){
27. projectItems.add(element);
28. }
29. }
30.
31. public void removeProjectItem(ProjectItem element){
32. projectItems.remove(element);
33. }
34.
35. public void accept(ProjectVisitor v){
36. v.visitTask(this);
37. }
38. }
The basic interface that defines the
Visitor
behavior is the
ProjectVisitor
. It defines a
visit
method for each
of the project classes.
Example A.122
ProjectVisitor.java
1. public interface ProjectVisitor{
2. public void visitDependentTask(DependentTask p);
3. public void visitDeliverable(Deliverable p);
4. public void visitTask(Task p);
5. public void visitProject(Project p);
6. }
With this framework in place, you can define classes that implement the
ProjectVisitor
interface and perform
some computation on project items. The class
ProjectCostVisitor
shows how project cost calculations could
be managed.
Example A.123
ProjectCostVisitor.java
1. public class ProjectCostVisitor implements ProjectVisitor{
2. private double totalCost;
3. private double hourlyRate;
4.
5. public double getHourlyRate(){ return hourlyRate; }
6. public double getTotalCost(){ return totalCost; }
7.
8. public void setHourlyRate(double rate){ hourlyRate = rate; }
9.
10. public void resetTotalCost(){ totalCost = 0.0; }
11.
12. public void visitDependentTask(DependentTask p){
13. double taskCost = p.getTimeRequired() * hourlyRate;
14. taskCost *= p.getDependencyWeightingFactor();
15. totalCost += taskCost;
16. }
17. public void visitDeliverable(Deliverable p){
18. totalCost += p.getMaterialsCost() + p.getProductionCost();
19. }
20. public void visitTask(Task p){
21. totalCost += p.getTimeRequired() * hourlyRate;
22. }
23. public void visitProject(Project p){ }
24. }
All behavior for the calculation, as well as variable storage, is centralized in the
Visitor
class. To add a new
behavior, you would create a new class that implements
ProjectVisitor
and redefine the four
visit
methods.
The
Contact
interface and
ContactImpl
class represent the owner for a
Task
or
Deliverable
.
Example A.124
Contact.java
1. import java.io.Serializable;