Software Design Pattern By Example: Template Method
Explain Template Method Design Pattern in an easy-to-understand example
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:
The syntax must be valid for certain plain-text files (e.g. XML, Ruby scripts)
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 isstd: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
Onesave()
method does the actual file saving, the othersafe_save()
validates the file content (and apply reformatting if it is okay) then callsave()
. The content of two other methodsvalidate()
andreformat()
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.