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
Strategyobjects. - Facilitates design change; if the strategy pattern was latter changed to another design, say inheritance, the client code wouldn't change, only the factory.
Aucun commentaire:
Enregistrer un commentaire