Template pattern
Key 4: Refining algorithm to use case.
In this pattern, we define the skeleton of an algorithm in a method called the template
method, which defers some of its steps to subclasses. How we do this is as follows, we analyze the procedure, and break it down to logical steps, which are different for different use cases. Now, we may or may not implement the default implementation of these steps in the main class. The subclasses of the main class will implement the steps that are not implemented in the main class, and they may skip some generic steps implementation. In the following example, AlooDish
is base class with the cook
template method. It applies to normal Aloo fried dishes, which have a common cooking procedure. Each recipe is a bit different in ingredients, time to cook, and so on. Two variants, AlooMatar
, and AlooPyaz
, define some set of steps differently than others:
import six class AlooDish(object): def get_ingredients(self,): self.ingredients = {...