概念
策略模式:定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化不会影响到用算法的客户。
注意:与简单工厂模式相比,使用上只需要知道 Context 类即可
应用场景
- 算法会时常变动;
- 用几个类封装了这些算法且有共同的父类;
一般步骤
抽象一个算法类
class Strategy { public: virtual void Algorithm()=0; };
写具体的子类
class ConcreateStrategyA : public Strategy { public: void Algorithm() { printf("ConcreateStrategyA \n"); } }; class ConcreateStrategyB : public Strategy { public: void Algorithm() { printf("ConcreateStrategyB \n"); } }; class ConcreateStrategyC : public Strategy { public: void Algorithm() { printf("ConcreateStrategyC \n"); } };
创建一个类,根据不同条件调用不同的策略
class Context { public: Context(char algorithm) { this->algorithm = algorithm; switch (algorithm) { case 'A': this->strategy = new ConcreateStrategyA(); break; case 'B': this->strategy = new ConcreateStrategyB(); break; case 'C': this->strategy = new ConcreateStrategyC(); break; default: this->strategy = NULL; break; } } ~Context() { printf("delete strategy%c\n",algorithm); delete strategy; } void ContextInterface() { strategy->Algorithm(); } private: Strategy *strategy; char algorithm; };
具体实例
#include <cstdio> class Strategy // 抽象类-策略类 { public: virtual void Algorithm()=0; }; class ConcreateStrategyA : public Strategy // 策略A { public: void Algorithm() { printf("ConcreateStrategyA \n"); } }; class ConcreateStrategyB : public Strategy // 策略B { public: void Algorithm() { printf("ConcreateStrategyB \n"); } }; class ConcreateStrategyC : public Strategy // 策略C { public: void Algorithm() { printf("ConcreateStrategyC \n"); } }; #if 0 class Context { public: Context(Strategy *strategy) { this->strategy = strategy; } ~Context() { delete strategy; } void ContextInterface() { strategy->Algorithm(); } private: Strategy *strategy; }; int main() { Context *context = NULL; context = new Context(new ConcreateStrategyA()); context->ContextInterface(); context = new Context(new ConcreateStrategyB()); context->ContextInterface(); context = new Context(new ConcreateStrategyC()); context->ContextInterface(); return 0; } #else class Context // 使用策略的类 { public: Context(char algorithm) { this->algorithm = algorithm; switch (algorithm) { case 'A': this->strategy = new ConcreateStrategyA(); break; case 'B': this->strategy = new ConcreateStrategyB(); break; case 'C': this->strategy = new ConcreateStrategyC(); break; default: this->strategy = NULL; break; } } ~Context() { printf("delete strategy%c\n",algorithm); delete strategy; } void ContextInterface() { strategy->Algorithm(); } private: Strategy *strategy; char algorithm; }; int main() { Context *context = NULL; context = new Context('A'); context->ContextInterface(); delete context; context = new Context('B'); context->ContextInterface(); delete context; context = new Context('C'); context->ContextInterface(); delete context; return 0; } #endif
总结
策略模式是一种定义了一系列算法的方法,它可以以相同的方式调用所有的算法,减少各种算法类与使用算法类之间的耦合。 --《大话设计模式》
策略模式的 Strategy类层次为 Context 类定义了一系列可供重用的算法和行为。继承有助于析取出这些算法中的公共功能。
参考资料:
《大话设计模式》