Template Method

If you have enough Strategy objects, you might see repetition in their operational details. Some elements could repeat across multiple strategies, and some structures seem like boilerplate. I shall give examples of the issues through a Restaurant Meal class.

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 Template Method to provide hooks to hang the details. By finding the expected pattern of operations, you can make some steps virtual and override them.

Template Example

Because the GoF book is about object-oriented designs, it does not mention how to construct a Template Method object without inheritance. You may use an array or dictionary of callbacks. In this case, rather than sub-classing the AbstractTemplateClass to implement the details of the steps, you can use Strategy or Command objects to define the specific behaviour. Use a Prototype to retain the dynamicism while increasing type-safety.

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 …”