Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In a typical strategy pattern class Strategy { public: virtual int execute() con

ID: 659099 • Letter: I

Question

In a typical strategy pattern

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

class StrategyA : public Strategy
{
public:
    int execute() const override;
}

class StrategyB : public Strategy
{
public:
    int execute() const override;
}

class Context
{
public:
    Context() = delete;
    Context(Strategy* the_strategy);
    int execute() const;
private:
    Strategy* the_strategy_;
}
Should it be preferred to use a Context factory with the correct strategy injected

class ContextFactory
{
public:
    std::unique_ptr<Context> make(/*some parameters*/);
}

void ContextUser(/*some parameters*/)
{
    ContextFactory a_context_factory;
    auto a_context = a_context_factory.make(/*some parameters*/);
}
or a Strategy factory, leaving injection to the caller?

class StrategyFactory
{
public:
    std::unique_ptr<Strategy> make(/*some parameters*/);
}

void ContextUser(/*some parameters*/)
{
    StrategyFactory a_strategy_factory;
    Context a_context(a_strategy_factory.make(/*some parameters*/));
}
It seems to me the Context factory should be preferred as:

Less work for the caller.
Factory can manage lifetime of Strategy objects.
Facilitates design change; if the strategy pattern was latter changed to another design, say inheritance, the client code wouldn't change, only the factory.

Explanation / Answer

You bind your factory to Context. Here's some disadvantages for your consideration.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote