Facebook Pixel

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

CommandBehaviorOutput
["make", "coffee"]Runs Coffee.prepare() — four steps in orderfour lines
["make", "tea"]Runs Tea.prepare() — four steps in orderfour lines
["make", "<other>"]Unknown drinkUnknown 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".

Example
Input
2
make coffee
make tea
Output
Boil water
Brew coffee grounds
Pour into cup
Add sugar and milk
Boil water
Steep the tea
Pour into cup
Add lemon
Explanation
The first `make coffee` calls `Coffee.prepare()`. The template method fires the four steps in order: the shared `boil()` returns `"Boil water"`, then `Coffee.brew()` returns `"Brew coffee grounds"`, then the shared `pour()` returns `"Pour into cup"`, then `Coffee.addCondiments()` returns `"Add sugar and milk"`. The second `make tea` follows the same skeleton but calls `Tea.brew()` and `Tea.addCondiments()` for the varying steps. Each `make` prints the four steps in order.

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.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro