Search⌘ K
AI Features

The Template Pattern

Explore the Template pattern in Python to apply the DRY principle by structuring common algorithm steps in a base class and customizing varying parts in subclasses. Learn how this pattern supports code reuse and flexibility through an example of a car sales reporter using SQLite.

We'll cover the following...

Overview

The Template pattern (sometimes called the Template method) is useful for removing duplicate code; it’s intended to support the Don’t Repeat Yourself (DRY) principle. It is designed for situations where we have several different tasks to accomplish that have some, but not all, steps in common. The common steps are implemented in a base class, and the distinct steps are overridden in subclasses to provide custom behavior. In some ways, it’s like the Strategy pattern, except similar sections of the algorithms are shared using a base class. Here it is in the UML format:

The UML diagram of the Template pattern
The UML diagram of the Template pattern

A Template example

Let’s create a car sales reporter as an example. We can store records of sales in an SQLite database table. SQLite is the built-in database engine that allows us to store records using SQL syntax.

We have two common tasks we need to perform:

  • Select all sales of new vehicles and output them to the screen in a comma-delimited format
  • Output a comma-delimited list of all salespeople with their gross sales and save it to a
...