Strategy


Description:

Encapsulates an algorithm inside a class

Intent

  • Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
  • Capture the abstraction in an interface, bury implementation details in derived classes.

Example:

Note

Idea:

Check list

  1. Identify an algorithm (i.e. a behavior) that the client would prefer to access through a "flex point".
  2. Specify the signature for that algorithm in an interface.
  3. Bury the alternative implementation details in derived classes.
  4. Clients of the algorithm couple themselves to the interface.

Code:

#include <iostream>
#include <memory>
#include <vector>
#include <cmath>

using namespace std;

class StrategyInterface{
public:
    virtual void execute() const = 0;
    virtual ~StrategyInterface() {}
};

class StrategyA: public StrategyInterface{
public:
    void execute() const override {
        cout << "Called StrategyA execute method" << endl;
    }
};

class StrategyB: public StrategyInterface{
public:
    void execute() const override {
        cout << "Called StrategyB execute method" << endl;
    }
};

class StrategyC: public StrategyInterface{
public:
    void execute() const override {
        cout << "Called StrategyC execute method" << endl;
    }
};

class Context{
private:
    StrategyInterface * strategy_;
public:
    Context(StrategyInterface * s): strategy_(s) {}
    void set_strategy(StrategyInterface * s){ strategy_ = s; }
    void execute() const { strategy_->execute(); }
};

int main(){
    StrategyA strategy_A;
    StrategyB strategy_B;
    StrategyC strategy_C;

    Context context_A(&strategy_A);
    Context context_B(&strategy_B);
    Context context_C(&strategy_C);

    context_A.execute(); // output: "Called StrategyA execute method"
    context_B.execute(); // output: "Called StrategyB execute method"
    context_C.execute(); // output: "Called StrategyC execute method"

    context_A.set_strategy(&strategy_B);
    context_A.execute(); // output: "Called StrategyB execute method"
    context_A.set_strategy(&strategy_C);
    context_A.execute(); // output: "Called StrategyC execute method"    
}

results matching ""

    No results matching ""