Template Method
If you have enough
Many meals can have the same dessert, starter, or even main:
- Salad_Steak_IceCream
- Salad_ChickenPie_IceCream
- PrawnCocktail_Risotto_Brownie
- Toast_ChickenPie_Brownie
- Toast_Steak_CheeseCake
Repeating elements in the requirements means repeating elements in the objects which are not satisfying to implement. However, the parts of the meals are not the only repeating thing.
Every strategy will empty the table before serving the next course. But clearing the table is not part of the specifics of any meal. Also, every meal has three courses. It could be a general structure to what every strategy does, and it looks like boilerplate code in every meal.
A dutiful programmer would then think to reduce the repetition. It’s error-prone, after all. But how can you remove repetition when it’s the when-and-with-what, not the how?
Introduce a
Because the GoF book is about object-oriented designs, it does not mention how
to construct a AbstractTemplateClass
to implement the details of the steps, you can use
meal_dict = {
"Starter": PrawnCocktail,
"Main": Risotto,
"Dessert":CheeseCake,
}
def MealTime(meal_dict):
PlaceCutlery()
meal["Starter"]()
Cleanup()
meal["Main"]()
Cleanup()
meal["Dessert"]()
Cleanup()
“We’re going to cook a roast. So, first, pre-heat whatever you’re going to cook it in. Second, season whatever meat you’re cooking …”