Java Reference
In-Depth Information
This can be illustrated with a simple example. Let's say you've written some code to get a list of
expenses your company has incurred from a database, which you store in a List<Expense> object.
You know that management will want to run different kinds of statistics on this list of expenses.
What is the total sum of all expenses? How many different receiving companies are involved? How
many products of a certain type were purchased? And so on. In any case, you realize that the gen-
eral structure of all these questions is the same: you loop through the list, do something with every
expense, and present the result. As such, you could make this type of template method:
import java.util.List;
public abstract class ExpenseListCalculator {
public final double calculate(List<Expense> expenses) {
initialize();
for (Expense expense : expenses) {
handle(expense);
}
return getResult();
}
protected abstract void initialize();
protected abstract void handle(Expense expense);
protected abstract double getResult();
}
Calculating the total sum of all expenses would now look like this:
public class ExpenseTotalSumCalculator extends ExpenseListCalculator {
private double total;
@Override
protected void initialize() {
total = 0;
}
@Override
protected void handle(Expense expense) {
total += expense.getTotalPrice();
}
@Override
protected double getResult() {
return total;
}
}
Finding the amount of expense lines related to a given product is similarly easy:
public class ExpenseProductCountCalculator extends ExpenseListCalculator {
private double count;
private String product;
Search WWH ::




Custom Search