给定一个典型的战略格局应该在策略模式中使用安全指针吗?
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;
}
我相信“前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'?那么,没有歧义! – Nim 2015-02-06 11:31:38