【发布时间】:2015-02-06 11:24:23
【问题描述】:
给定一个典型的策略模式
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;
}
我相信实现上下文类的“pre-C++11”方式类似于
class ContextRaw
{
public:
ContextRaw(Strategy* the_strategy);
~ContextRaw(); // Should this delete the_strategy_?
int execute() const;
private:
Strategy* the_strategy_;
}
对我来说,在这个设计中,Context 是否应该对Strategy 负责并不清楚,除非有明确的文档说明,否则可能会发生不好的事情
void trouble()
{
StrategyA a_concrete_strategy;
ContextRaw a_context(&a_concrete_strategy); // Oops, Context may try to delete stack variable
}
void more_trouble()
{
Strategy* a_concrete_strategy = new StrategyA;
ContextRaw* a_context = new ContextRaw(a_concrete_strategy);
ContextRaw* another_context = new ContextRaw(a_concrete_strategy);
delete a_context;
std::cout << another_context.execute() << std::endl; // Oops, the_strategy is deleted
}
鉴于安全指针,现在是否应该注入一个安全指针并让Context 拥有Strategy 的所有权?
class ContextUnique
{
public:
ContextUnique() = delete;
ContextUnique(std::unique_ptr<Strategy> the_strategy);
~ContextUnique();
int execute() const;
private:
std::unique_ptr<Strategy> the_strategy_;
}
或者如果Strategy 可以在不同的Context 之间共享?
class ContextShared
{
public:
ContextShared() = delete;
ContextShared(std::shared_ptr<Strategy> the_strategy);
~ContextShared();
int execute() const;
private:
std::shared_ptr<Strategy> the_strategy_;
}
这种设计当然引入了它自己的问题,特别是只有动态分配的Strategy才能注入Context。
【问题讨论】:
-
为什么
Context不通过reference 获取Strategy?那么,没有歧义!
标签: c++ c++11 design-patterns strategy-pattern