Should factory make context or concrete strategies objects in strategy-factory pattern?
https://softwareengineering.stackexchange.com/questions/272305
-
07-10-2020 - |
题
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.
解决方案
You bind your factory to Context
. Here's some disadvantages for your consideration.
- More annoying to implement factories.
- If you want to reuse the strategies for something other than
Context
, you have a problem. - 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.