为什么有人会比静态策略更喜欢静态策略?

#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();
}

这是用c ++编写的静态和动态策略模式的示例。我不知道为什么有人会使用静态策略而不是动态策略。动态策略似乎可以完成静态策略的所有工作,但由于可以在运行时更改策略,因此它具有更大的灵活性。谁能给我一个例子,其中静态策略比动态策略更好?

评论