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 ContextRaw
{
public:
ContextRaw(Strategy* the_strategy);
~ContextRaw(); // Should this delete the_strategy_?
int execute() const;
private:
Strategy* the_strategy_;
}
뭔가를 컨텍스트 클래스를 구현하는 '사전 C++ (11)'방식을 감안할 때,이 디자인은 아니에요 Strategy
에 대해 Context
이 책임이 있는지 확인하고, 명확한 문서가 없으면 나쁜 일이 발생할 수 있습니다.
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_;
}
물론이 디자인은 특히 동적으로들 Context
에 주입 할 수 Strategy
'을 할당, 그것의 자신의 문제를 소개합니다.
왜'Context'는 * reference *에 의해'Strategy'를 취하지 않을까요? 그럼, 모호성! – Nim