Design Patterns in C++: Strategy

Design Patterns in C++: Strategy

The Strategy Pattern allows you to change an algorithm at runtime. Image for example some algorithms to calculate the square root, as you may know there are plenty of it. They all do the same, but they all have their own upsides and downsides – one is more accurate, the other one is less expensive (computation time).

Normally, you have to choose your color at the beginning (at least at playing ludo) – right? So if you have decided for one algorithm – you have to keep it till the end.

But sometimes you need to change something at runtime, e.g. when your kid is noticing that he/she really really hates that ugly green the token has – the bluish one would be so much better!

Using the Strategy Pattern that is not a problem, as long as they have the same interface (shape, size, purpose in the sense of ludo).

// g++ -std=gnu++11 strategy.cpp -o strategy

#include <iostream>
#include <memory>

using namespace std;

class Token {
public:
    virtual void color()() = 0;
    virtual ~Token() {}
};

class GreenToken : public Token {
public:
    void operator()() { cout << "ugly green, nobody ever won using green...\n"; }
};

class BlueToken : public Token {
public:
    void operator()() { cout << "oh what a wonderful blue, here we go!\n"; }
};

class YellowToken : public Token {
public:
    void operator()() { cout << "pff... yellow\n"; }
};

class Player {
    shared_ptr<Token> _strat;
public:
    Player() : _strat(nullptr) {}
    void setStrategy(shared_ptr<Token> strat)  { _strat = strat; }
    void strategy()  { if (_strat) (*_strat)(); }
};

int main() {
    Player * kiddo = new Player();

    kiddo->setStrategy( std::shared_ptr<Token>(new GreenToken) );
    kiddo->strategy();

    kiddo->setStrategy( std::shared_ptr<Token>(new BlueToken) );
    kiddo->strategy();
}

Unglücklicherweise ist dieser Eintrag noch nicht ganz fertig, bitte habt ein wenig Geduld.

Unfortunately this entry is not yet finished – stay tuned.