The Agile Way

The Agile Way

Share this post

The Agile Way
The Agile Way
Software Design Pattern By Example: Template Method
Copy link
Facebook
Email
Notes
More

Software Design Pattern By Example: Template Method

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

Zhimin Zhan's avatar
Zhimin Zhan
Nov 15, 2022
∙ Paid
1

Share this post

The Agile Way
The Agile Way
Software Design Pattern By Example: Template Method
Copy link
Facebook
Email
Notes
More
Share
caption...

A repost of my past article on Medium.

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

Let’s look at a typical design from programmers new to Object Oriented Programming.

Keep reading with a 7-day free trial

Subscribe to The Agile Way to keep reading this post and get 7 days of free access to the full post archives.

Already a paid subscriber? Sign in
© 2025 Zhimin Zhan
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share

Copy link
Facebook
Email
Notes
More