The Strategy Pattern is a behavioral design pattern from the book Design Patterns: Elements of Reusable Object-Oriented Software”. It defines a family of algorithms and encapsulates them in objects.
The Strategy Pattern is heavily used in the Standard Template Library.
The Strategy Pattern
- Defines a family of algorithms and encapsulates them in objects
Also known as
- Different variations of an algorithm are needed
- The client does not need to know the algorithm
- The algorithm should be exchangeable at the run time of a program
- Defines the interface for the family of algorithms
- Implements an algorithm
- Manages a reference to a
- Has a
Context has a
ConcreteStrategy that is encapsulated in an object. The
ConcreteStrategy implements the interface of
Strategy. Typically, the
ConcreteStrategy can be adjusted during run time.
The following example
strategy.cpp uses three concrete strategies and follows the naming conventions in the previous image.
Context has a strategy (line 1) that can be set (line 2) and can be executed (line 3). Each strategy has to support the member function
execute (line 4). The
main program uses three concrete strategies, sets them, and executes them. Here is the output of the program.
Usage in C++
The Strategy Pattern is heavily used in the Standard Template Library. In the case of templates, we call it Policy.
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 policies in C++.
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. My previous post “Hash Functions” gives you more information about
Consequentially, you can use a user-defined data type such as
MyInt as a key in a
I implemented the hash function (line 1), and the equal function (line 2) as a function object and overloaded, for convenience reasons, the output operator (line 3). Line 4 creates out of all components a new type MyIntMap, that uses
MyInt as a
key. The following screenshot shows the output of the instance
- The Template Method and Strategy Pattern use cases are pretty similar. Both patterns enable it to provide variations of an algorithm. The Template Method is based on a class level by subclassing, and the Strategy Pattern on an object level by composition. The Strategy Pattern gets is various strategies as objects and can, therefore, exchange its strategies at run time. The Template Method inverts the control flow, following the hollywood principle: “Don’t call us, we will call you”. The Strategy Pattern is often a black box. It allows you to replace one strategy with another without knowing its details.
- The Bridge Pattern and the Strategy Pattern have identical structures but different intents. The Bridge Pattern is a structural pattern and aims to decouple physical dependencies, the Strategy Pattern is a behavioral pattern that decouples logical dependencies and allows to injection of external implementations.
Let’s talk about the pros and cons of the Strategy Pattern.
Pros and Cons
- Algorithms are encapsulated in objects and can be exchanged during run time
- Adding new strategies is easy. You only have to implement a new strategy.
- The Strategy Pattern replaces conditional execution based on
- Callables are often lightweight implementations for strategies in C++:
The program uses the function
greater, the predefined function object
std::greater<std::string>, and a lambda expression (line 1) to sort a
std::vector<std::string> in descending way. The callables are, in this example, binary predicates.
- Clients must know and choose the right strategy
- The number of objects (strategies) increases heavily
I presented in my last posts the following Design Patterns from the seminal book “Design Patterns: Elements of Reusable Object-Oriented Software“.
The ones listed here are the ones most relevant in my past. In my next post, I will write about idioms in C++. An idiom is an implementation of an architecture or design pattern in a concrete programming language.
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, and Bhavith C Achar.
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,