Design Patterns 21: Strategy
阿新 • • 發佈:2018-12-15
定義一組演算法,使得演算法之間具有互換性。
struct Strategy { virtual void AlgorithmInterface() = 0; }; struct ConcreteStrategyA : Strategy { void AlgorithmInterface() override {} }; struct ConcreteStrategyB : Strategy { void AlgorithmInterface() override {} }; struct Context { void ContextInterface() { _strategy->AlgorithmInterface(); } void SetStrategy(Strategy* strategy) { _strategy = strategy; } Context(Strategy* strategy) : _strategy(strategy) {} private: Strategy* _strategy; }; int main() { Context context(new ConcreteStrategyA); context.ContextInterface();//ConcreteStrategyA::AlgorithmInterface() get called context.SetStrategy(new ConcreteStrategyB); context.ContextInterface();//ConcreteStrategyB::AlgorithmInterface() get called }