Java Reference
In-Depth Information
Template Method
This example uses project classes from the Personal Information Manager to illustrate the Template Method.
ProjectItem is the abstract class that defines the Template Method in this demonstration. Its method
getCostEstimate returns a total value for the project item that is calculated using the following equation:
time estimate * hourly rate + materials cost
The hourly rate is defined in the ProjectItem class (using the rate variable, getter and setter methods in the
class), but the methods getTimeRequired and getMaterialsCost are abstract. This requires the subclasses to
override them, providing their own way to calculate the values.
Example A.129 ProjectItem.java
1. import java.io.Serializable;
2. public abstract class ProjectItem implements Serializable{
3. private String name;
4. private String description;
5. private double rate;
6.
7. public ProjectItem(){}
8. public ProjectItem(String newName, String newDescription, double newRate){
9. name = newName;
10. description = newDescription;
11. rate = newRate;
12. }
13.
14. public void setName(String newName){ name = newName; }
15. public void setDescription(String newDescription){ description = newDescription; }
16. public void setRate(double newRate){ rate = newRate; }
17.
18. public String getName(){ return name; }
19. public String getDescription(){ return description; }
20. public final double getCostEstimate(){
21. return getTimeRequired() * getRate() + getMaterialsCost();
22. }
23. public double getRate(){ return rate; }
24.
25. public String toString(){ return getName(); }
26.
27. public abstract double getTimeRequired();
28. public abstract double getMaterialsCost();
29. }
The Deliverable class represents a concrete product of some kind. Because it represents a physical item, the
value returned by its getTimeRequired method is a fixed amount. Similarly, the getMaterialsCost method
returns a fixed value.
Example A.130 Deliverable.java
1. public class Deliverable extends ProjectItem{
2. private double materialsCost;
3. private double productionTime;
4.
5. public Deliverable(){ }
6. public Deliverable(String newName, String newDescription,
7. double newMaterialsCost, double newProductionTime,
8. double newRate){
9. super(newName, newDescription, newRate);
10. materialsCost = newMaterialsCost;
11. productionTime = newProductionTime;
12. }
13.
14. public void setMaterialsCost(double newCost){ materialsCost = newCost; }
15. public void setProductionTime(double newTime){ productionTime = newTime; }
16.
17. public double getMaterialsCost(){ return materialsCost; }
18. public double getTimeRequired(){ return productionTime; }
19. }
 
Search WWH ::




Custom Search