給定一個典型的戰略格局應該在策略模式中使用安全指針嗎?
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