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:

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

解决方案

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

  1. More annoying to implement factories.
  2. If you want to reuse the strategies for something other than Context, you have a problem.
  3. If Context needs a second, independent strategy, you have a problem. With one factory responsible for creating the context, you now need N*M factories, one for each strategy combination.
许可以下: CC-BY-SA归因
scroll top