The Strategy Pattern
This post is a cross-post from www.ModernesCpp.com.
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
Purpose
Also known as
Use case
?Structure
Strategy
ConcreteStrategy
Context
The 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.
Modernes C++ Mentoring
Stay Informed: Subscribe Here.
Example
The following example strategy.cpp uses three concrete strategies and follows the naming conventions in the previous image.
// strategy.cpp
#include <iostream>
#include <memory>
#include <utility>
class Strategy {
public:
virtual void execute() = 0; // (4)
virtual ~Strategy() {}
};
class Context {
std::unique_ptr<Strategy> strat{}; // (1)
public:
void setStrategy(std::unique_ptr<Strategy> strat_) { // (2)
strat = std::move(strat_); }
}
void strategy() { if (strat) strat->execute(); } // (3)
};
class Strategy1 : public Strategy {
public:
void execute() { std::cout << "Strategy1 executed\n"; }
};
class Strategy2 : public Strategy {
public:
void execute() { std::cout << "Strategy2 executed\n"; }
};
class Strategy3 : public Strategy {
public:
void execute() { std::cout << "Strategy3 executed\n"; }
};
int main() {
std::cout << '\n';
Context k;
k.setStrategy(std::make_unique<Strategy1>());
k.strategy();
k.setStrategy(std::make_unique<Strategy2>());
k.strategy();
k.setStrategy(std::make_unique<Strategy3>());
k.strategy();
std::cout << '\n';
}
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::vector and std::unordered_map exemplifies policies in C++.
template<class T, class Allocator = std::allocator<T>> // (1)
class vector;
template<class Key,
class T,
class Hash = std::hash<Key>, // (3)
class KeyEqual = std::equal_to<Key>, // (4)
class allocator = std::allocator<std::pair<const Key, T>> // (2)
class unordered_map;
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 std::unordered_map.
Consequentially, you can use a user-defined data type such as MyInt as a key in a std::unordered_map.
领英推荐
// templatesPolicy.cpp
#include <iostream>
#include <unordered_map>
struct MyInt{
explicit MyInt(int v):val(v){}
int val;
};
struct MyHash{ // (1)
std::size_t operator()(MyInt m) const {
std::hash<int> hashVal;
return hashVal(m.val);
}
};
struct MyEqual{
bool operator () (const MyInt& fir, const MyInt& sec) const { // (2)
return fir.val == sec.val;
}
};
std::ostream& operator << (std::ostream& strm, const MyInt& myIn){ // (3)
strm << "MyInt(" << myIn.val << ")";
return strm;
}
int main(){
std::cout << '\n';
using MyIntMap = std::unordered_map<MyInt, int, MyHash, MyEqual>; // (4)
std::cout << "MyIntMap: ";
MyIntMap myMap{{MyInt(-2), -2}, {MyInt(-1), -1}, {MyInt(0), 0}, {MyInt(1), 1}};
for(auto m : myMap) std::cout << '{' << m.first << ", " << m.second << "}";
std::cout << "\n\n";
}
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 myMap.
Related Patterns
Let's talk about the pros and cons of the Strategy Pattern.
Pros and Cons
Pros
// sortVariations.cpp
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
bool greater(const std::string& first, const std::string& second) {
return first > second;
}
int main(){
std::vector<std::string> myStrings{"Only", "for", "testing", "purpose", "."};
// sort ascending
std::sort(myStrings.begin(), myStrings.end());
// sort descending // (1)
std::sort(myStrings.begin(), myStrings.end(), greater);
std::sort(myStrings.begin(), myStrings.end(), std::greater<std::string>());
std::sort(myStrings.begin(), myStrings.end(), [](const std::string& first, const std::string& second) {
return first > second;
});
// sort based on the length of the strings
std::sort(myStrings.begin(), myStrings.end(), [](const std::string& first, const std::string& second) {
return first.length() < second.length();
});
}
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.
Cons
What's Next?
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, Marko, G Prvulovic, Reinhold Dr?ge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, 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, Evangelos Denaxas, 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, and Phillip Diekmann.
Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, Ralf Abramowitsch, John Nebel, Mipko, and Alicja Kaminska.
My special thanks to Embarcadero
My special thanks to PVS-Studio
?
Seminars
I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
Bookable (Online)
German
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
New
Contact Me