Java Reference
In-Depth Information
Factory Method (page 21) - Template methods often call Factory Methods to create new instances without
knowing the exact class being created.
Strategy (page 114) - The Strategy pattern uses composition to completely replace behavior, while the Template
Method pattern uses inheritance to replace parts of the behavior.
Intercepting Filter [CJ2EEP] - The Intercepting Filter uses the Template Method pattern to implement its
Template Filter Strategy.
Example
Note:
For a full working example of this code example, with additional supporting classes and/or a RunPattern class,
see “ Template Method ” on page 440 of the “ Full Code Examples ” appendix.
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 2.52 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 2.53 Deliverable.java
1. public class Deliverable extends ProjectItem{
2. private double materialsCost;
3. private double productionTime;
Search WWH ::




Custom Search