BehavioralPattern

The Strategy Pattern

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.

 BehavioralPattern

The Strategy Pattern is heavily used in the Standard Template Library.

The Strategy Pattern

Purpose

  • Defines a family of algorithms and encapsulates them in objects

Also known as

  • Policy

Use case

  • 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

 Structure

Strategy

Strategy

  • Defines the interface for the family of algorithms

ConcreteStrategy

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

    • Implements an algorithm

    Context

    • Manages a reference to a ConcreteStrategy
    • Has a ConcreteStrategy

    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.

    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.

    strategyExample

    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.

    templatesPolicy

    Related Patterns

    • 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

    Pros

    • 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 if/else statements or switch statements
    • Callables are often lightweight implementations for strategies in C++:

    // 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

    • Clients must know and choose the right strategy
    • The number of objects (strategies) increases heavily

    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“.

    15DesignPattern

     

    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, Bhavith C Achar, Marco Parri Empoli, moon, and Philipp Lenk.

    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
    My special thanks to SHAVEDYAKS

    Seminars

    I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

    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++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *