Overview
The Template Method Design Pattern is a behavioral pattern that provides a way to define the skeleton of an algorithm in a base class and allows subclasses to override some steps of the algorithm. This pattern is useful when you have a set of algorithms with similar main steps but different implementation details.
The Template Method Design Pattern uses inheritance to create a common template that can be customized by subclasses. General steps of the algorithm are defined in a base class and subclasses provide specific steps implementation details.
For example, let’s say we want to create a reporting system that supports reports generated in different formats, like HTML, PDF, and TXT. Each report generation follows the same steps:
- Open the report
- Create header
- Create body
- Create footer
- Close the report
Implementation details on header, body, and footer creation are different. However, the main flow of steps in creating a report is the same. Therefore, we can use the Template Method Design Pattern to decompose this problem using Object-Oriented Programming (OOP) paradigm.
More on this pattern…
To read more on this and the other patterns, get “GoF Design Patterns Distilled” book from Amazon or Leanpub: