Member-only story

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

This article is also on Substack.

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 ...

So how can we design the safe ‘Save Project’ button in an object-oriented language?

Analyse & Prepare

  • A list of project files
    We need a data structure to store a list of project files. A good candidate is std:list from the C++ Standard Template Library (STL).
std::list<std::string> products;
products.push_back("foo");
products.push_back("bar");
products.insert(0, "hello world");
// products => ["hello world", "foo", "bar"]
  • Traverse a list
    The below is a C+11 (and later) way of traversing a list.
for (auto prod : products)
std::cout << prod << "\n"
  • Two save methods
    One save() method does the actual file saving, the other safe_save() validates the file content (and apply reformatting if it is okay) then call save(). The content of two other methods validate() and reformat() are just a single line of printing text.

Sub-optimal Design

--

--

Zhimin Zhan
Zhimin Zhan

Written by Zhimin Zhan

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

No responses yet

Write a response