Software Design Pattern By Example: Template Method

Explain Template Method Design Pattern in an easy-to-understand example

Zhimin Zhan
5 min readJan 24, 2022

--

A repost of my daughter’s article with permission. I added it here for the convenience of my blog subscribers.

Table of Contents:· The Problem: Safe Save
· Analyse & Prepare
· Sub-optimal Design
Strategy pattern not optimal here
· Template Method Pattern
- Python Version

Example Problem: Safe Save

An online editor has a ‘Save Project’ button, which will save all open files. The rules for our safe save are:

  1. The syntax must be valid for certain plain-text files (e.g. XML, Ruby scripts)
  2. Try to reformat (pretty-print) the document, but only if the syntax is valid and feasible

Note: the actual code logic of validation/reformatting is not necessary, just print a line that represents the process.

Here is a sample output of ‘Save Project’ (files: foo.xml, wise.pdf, bar.rb):

[XmlFile] Validate
[XmlFile] Reformatting ...
{foo.xml} Saving ...
[PdfFile] Skip validate
{wise.pdf} not saved ...
[RubyFile] Validate
[RubyFile] Reformatting ...
{bar.rb} Saving ...

--

--

Zhimin Zhan

Test automation & CT coach, author, speaker and award-winning software developer. Help teams succeed with Agile/DevOps by implementing real Continuous Testing.