Design Patterns

Template Method



Design Pattern Type: Behavioral

GoF Statement of Intent:


Define the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
Brief Overview:



Defines the program skeleton of an algorithm, but one or more of the algorithm steps are overridden by subclasses that provide their own concrete implementation. A parent class is created that provides the abstract interface and defines the basic steps of the algorithm while the subclasses handle the specifics.
UML Diagram:

Discussion and In-class Example:

In the Template Method Design Pattern we our example of the StarBuzz coffee shop. StarBuzz has a StarbuzzBeverageRecipe class which contains an algorithm for preparing beverages. The process is virtually identical whether preparing coffee or tea. In order to apply the Template Method pattern we leave in the parent class all the actions that are the same for both beverages, but we defer to the subclasses those steps in the preparation algorithm that are unique to beverage type. Thus the brew() and addCondiments() functions which are different are delegated to the subclasses while the boiWater() and pourInCup() functions are just inherited directly from the parent class.