Exercise: Template Method
This exercise puts the Template Method pattern into code.
Scenario
A beverage station prepares drinks by following a fixed four-step recipe: boil water,
brew the drink, pour it into a cup, and add condiments. The first and third steps are
identical for every drink; the second and fourth vary. An abstract Beverage base class
holds the recipe as a template method called prepare(), which calls boil(), brew(),
pour(), and addCondiments() in order. The two shared steps are implemented on the base.
The two varying steps are abstract, left for each concrete subclass to fill in.
Your task is to implement the two concrete subclasses — Coffee and Tea — so the
dispatcher can call prepare() on either one and get the correct four lines.
Commands
| Command | Behavior | Output |
|---|---|---|
["make", "coffee"] | Runs Coffee.prepare() — four steps in order | four lines |
["make", "tea"] | Runs Tea.prepare() — four steps in order | four lines |
["make", "<other>"] | Unknown drink | Unknown drink: <other> |
Each make command produces exactly four output lines (or one line for an unknown drink).
The fixed steps shared by all beverages are "Boil water" and "Pour into cup". Coffee
provides "Brew coffee grounds" and "Add sugar and milk"; tea provides "Steep the tea"
and "Add lemon".
2 make coffee make tea
Boil water Brew coffee grounds Pour into cup Add sugar and milk Boil water Steep the tea Pour into cup Add lemon
Your task
Create Coffee and Tea subclasses of Beverage, overriding brew() and
addCondiments() so the commands produce the output above. The starter keeps the
Beverage base with the template method prepare(), the shared boil() and pour()
implementations, and the dispatcher, marking where to add the two subclasses with a
TODO comment listing each class's method signatures and return values.