vendredi 24 avril 2020

Why would anyone prefer static strategy over the dynamic one?

#include <iostream>

class Strategy
{
public:
    virtual void execute() = 0;
};

class Strategy1 : public Strategy
{
public:

    virtual void execute() override { std::cout << "executed1\n"; }
};

class Strategy2 : public Strategy
{
public:

    virtual void execute() override { std::cout << "executed2\n"; }
};

template <typename S>
class StaticStrategy
{
    S strategy;

public:

    void execute()
    {
        strategy.execute();
    }
};

class DynamicStrategy
{
    Strategy* strategy;

public:

    DynamicStrategy(Strategy* strategy) : strategy(strategy) {}

    void execute()
    {
        strategy->execute();
    }

    void setStrategy(Strategy* newStrategy)
    {
        delete strategy;
        strategy = newStrategy;
    }

    ~DynamicStrategy()
    {
        delete strategy;
    }
};

int main()
{
    StaticStrategy<Strategy1> staticStrategy;
    staticStrategy.execute();

    DynamicStrategy dynamicStrategy(new Strategy1{});
    dynamicStrategy.execute();

    dynamicStrategy.setStrategy(new Strategy2{});
    dynamicStrategy.execute();
}

Here is an example of the static and the dynamic strategy pattern written in c++. I wonder why would someone use a static strategy instead of a dynamic one. It seems like the dynamic one does all the job of the static one but also have more flexibility since the strategy can be changed at run time. Can anyone give me an example where a static strategy would be better that a dynamic one?

Aucun commentaire:

Enregistrer un commentaire