Definition: The visitor pattern performs an operation on the objects within a collection (or other structure containing objects).
Usage: Use the visitor pattern to add capabilities to a composite of objects when encapsulation isn't important.
interface EdibleItem {
getAlcohol()
getCarbs()
getFat()
getProtein()
}
class Food implements EdibleItem {
getAlcohol() {return alcohol;}
getCarbs() {return carbs;}
getFat() {return fat;}
getProtein() {return protein;}
int alcohol, carbs, fat, protein;
}
class Meal implements EdibleItem {
getAlcohol() {return sum of alcohol in each food;}
getCarbs() {return sum of carbs in each food;}
getFat() {return sum of fat in each food;}
getProtein() {return sum of protein in each food;}
Food[] aFoodInThisMeal;
}
//this is the Visitor class
class CalorieCounter {
getCalories(EdibleItem item) {
return 7 * item.getAlcohol() + 4 * item.getCarbs() +
9 * item.getFat() + 4 * item.getProtein();
}
}
Since the interface EdibleItem doesn't contain a getCalories method, the class CalorieCounter adds it. It would also make perfect sense to include the getCalories method in the EdibleItem interface. If EdibleItem were an abstract class rather than an interface, the same method could be included just once and used by all EdibleItems.
However, the EdibleItem interface might be in third party code that cannot be modified.
By the way, if alcohol, carbs, fat, and protein are measured in grams and calories are "Calories" with a capital C (i.e. kilocalories) , CalorieCounter.getCalories is correct.
Copyright (C) 2008-2009 Steven Fletcher. All rights reserved.