Template Method Design Pattern


GoF Statement: Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets sub-classes redefine certain steps of an algorithm without changing the algorithm’s structure.
Category: Behavioral
UML Diagram:  

Description of the Demonstration:

Frequently in a program you will have two or more similar actions which must be performed. The algorithms for these actions may be almost identical with just a few steps that may vary. In this demonstration the class CaffeineBeverage provides the basic algorithm for preparing a hot beverage but lets the two sub-classes of Tea and Coffee handle those steps specific to their preparation, i.e. brew() and addCondiments() thus you do not have to duplicate code to handle the steps of the preparation algorithm, like boilWater and pourInCup, that are common to both sub-classes of CaffeineBeverage.


Code:

Click here to download a zip file containing all the source files and an executable of the Demonstration. See the _ReadMe.txt file in the zip.