| CSC 207 | Algorithms and Object Oriented Design | Spring 2009 |
Summary: In this lab, you will get a concrete look at another example of the builder pattern.
/**
* Meal models a typical fast-food chain value meal consisting of an
* entree, a side, and a drink.
*/
public class Meal {
private String entree = "";
private String side = "";
private String drink = "";
public void setEntree(String entree) {
this.entree = entree;
}
public void setSide(String side) {
this.side = side;
}
public void setDrink(String drink) {
this.drink = drink;
}
public String toString() {
return entree + " with a side of " + side + " and a " + drink;
}
}
Strings)
that need to be "built" in order to have a complete meal.
/** Abstract builder for the Meal objects, supporting all the
* operations for building a meal.
*/
public abstract class MealBuilder {
protected Meal theMeal;
// Additional methods here
}
Meal getMeal()void.
Should these methods be abstract or not?
/** Concrete builder for a meal with a burger, fries, and a cola. */
public class BurgerMealBuilder extends MealBuilder {
}
BurgerMealBuilder the implementations of the
three methods you defined in class MealBuilder that
end up setting the entree to "Burger",
the side to "Fries", and
the drink to "Cola".
HealthyMealBuilder that builds
a meal consisting of "Chicken Sandwich",
"Carrot Sticks", and "Diet Cola".
/** A cook that uses a builder for a meal to actually construct a meal
* and make it available.
*/
public class Cook {
private MealBuilder builder;
public void setMealBuilder (MealBuilder builder) {
this.builder = builder;
}
public Meal getMeal() {
return builder.getMeal();
}
public void constructMeal() {
// Take the necessary steps
}
}
MealBuilder object,
add code to the constructMeal method above that
(finally!) constructs the meal. You should have four
function calls! (Don't forget about 1.a)
/** A driver class for building some value meals */
public class BuilderExample {
public static void main(String[] args) {
Cook cook = new Cook();
Meal meal;
BurgerMealBuilder burgerBuilder = new BurgerMealBuilder();
HealthyMealBuilder healthyBuilder = new HealthyMealBuilder();
cook.setMealBuilder (burgerBuilder);
cook.constructMeal();
meal = cook.getMeal();
System.out.println("Order up! A " + meal);
cook.setMealBuilder (healthyBuilder);
cook.constructMeal();
meal = cook.getMeal();
System.out.println("Order up! A " + meal);
}
}
Order up! A Burger with a side of Fries and a Cola Order up! A Chicken Sandwich with a side of Carrot Sticks and a Diet Cola