The classics “Design Patterns: Elements of Reusable Object-Oriented Software”, and “Pattern-Oriented Software Architecture, Volume 1” use similar steps to present their pattern. Today, I will present this structure of a pattern.
Before I write about the structure of a pattern, let me bring you on the same page and start with the definition of a pattern according to Christopher Alexander.
- Patttern: “Each pattern is a three part rule, which expresses a relation between a certain context, a problem, and a solution.“
This means that a pattern describes a generic solution to a design problem that recurs in a particular context.
- The context is the design situation.
- The problem are the forces acting in this context.
- The solution is a configuration to balance the forces.
Christopher Alexander uses the three adjectives useful, usable and used to describe the benefits of patterns.
- Useful: A pattern needs to be useful.
- Usable: A pattern needs to be implementable.
- Used: Patterns are discovered, but not invented. This rule is called the rule of three: “A pattern can be called a pattern only if it has been applied to a real world solution at least three times.” (https://wiki.c2.com/?RuleOfThree)
Now, let me write about the structure of a pattern.
Structure of a Pattern
Honestly, there is a strange phenomenon. On the one hand, both books “Design Patterns: Elements of Reusable Object-Oriented Software” and “Pattern-Oriented Software Architecture, Volume 1” are the most influential books ever written about software development. On the other hand, both books have a great fall-asleep factor. This fall asleep factor is mainly due to the fact that both books present their patterns in monotonously repeating 13 steps.
In order to bore you not to death, I present these 13 steps concisely by applying the “Design Patterns: Elements of Reusable Object-Oriented Software” structure to the strategy pattern. The intention of each step is displayed in italic. The non-italic contents refer to the strategy pattern.
A concise name that is easy to remember.
An answer to the question: What is the purpose of the pattern?
Define a family of algorithms, encapsulate them in objects, and make them interchangeable at the run time of your program.
Also known as
Alternative names for the pattern if known.
A motivational example for the pattern.
A container of strings can be sorted in various ways. You can sort them lexicographically, case-insensitive, reverse, based on the length of the string, based on the first n characters … . Hard coding your sorting criteria into your sorting algorithm would be a maintenance nightmare. Consequentially, you make your sorting criteria an object that encapsulates the sorting criteria and configures your sorting algorithm with it.
Situations in which you can apply the pattern.
The strategy pattern is applicable when
- many related classes differ only in their behavior.
- you need different variants of an algorithm.
- the algorithms should be transparent to the client.
A graphical representation of the pattern.
Classes and objects that participate in this pattern.
Context: uses a concrete strategy, implementing the
Strategy: declares the interface for the various strategies
ConcreteStrategyA, ConcreteStrategyB: implements the strategy
Collaboration with the participants.
The context and the concrete strategy implement the chosen algorithm. The context forward client request to the used concrete strategy.
What are the pros and cons of the pattern?
The benefits of the strategy pattern are:
- Families of related algorithms can be used uniformly.
- The client is hidden from implementation details.
- The algorithms can be exchanged during run time.
Implementation techniques of the pattern.
- Define the context and the Strategy interface.
- Implement concrete strategies.
- The context can take its arguments at run time or at compile time as a template parameter.
Code snippets illustrating the implementation of the pattern. This book uses Smalltalk and C++.
The strategy pattern is so baked in the design of the Standard Template Library that we may not see it. Additionally, the STL often uses lightweight variants of the strategy pattern.
Here are two of many examples:
std::sort can be parametrized with a sorting criterion. The sorting criteria must be a binary predicate. Lambdas are perfect fits for such binary predicates:
strategySorting.cpp sorts the vector lexicographically, case-insensitive, ascending based on the length of the strings, and in reverse order. For the reverse sorting, I use the predefined function object
std::greater. The output of the program is directly displayed in the source code.
A policy is a generic function or class whose behavior can be configured. Typically, there are default values for the policy parameters.
std::unordered_map exemplifies these policies in C++. Of course, a policy is a strategy configured at compile time on template parameters.
This means each container has a default allocator for its elements, depending on
T (line 1) or on
std::pair<const Key, T> (line 2). Additionally,
std::unorderd_map has a default hash function (line 3) and a default equal function (4). The hash function calculates the hash value based on the key, and the equal function deals with collisions in the buckets.
At least two examples of known use of the pattern.
There are way more use cases of strategies in modern C++.
- In C++17, you can configure about 70 of the STL algorithms with an execution policy. Here is one overload of
Thanks to the execution policy, you can sort sequentially
(std::execution::seq), parallel (
std::execution::par), or parallel and vectorized (
- In C++20, most of the classic STL algorithms have a ranges pendant. These ranges pendants support additional customization points such as projections. Read more about them in my previous post, “Projection with Ranges“.
Patterns that are closely related to this pattern.
Strategy objects should be lightweight objects. Consequentially, lambda expressions are an ideal fit.
You may wonder, what is the difference between a pattern, an algorithm, or a framework? Let me clarify this in my next post and introduce terms such as pattern sequences and pattern languages.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, and Marco Parri Empoli.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,