在GOF的《设计模式:可复用面向对象软件的基础》一书中对策略模式是这样说的:定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。该模式使得算法可独立于使用它的客户而变化。
#include<iostream> using namespace std; enum strategy { Strategy1; Strategy2; Strategy3; }; //Context:使用一个ConcreteStrategy对象来配置;维护一个对Stategy对象的引用,同时,可以定义一个接口来让Stategy访问它的数据。 class context { public: context(strategy type) { switch type { case Strategy1: pStrategy=new ConcreteStrategy1(); break; case Strategy2: pStrategy=new ConcreteStrategy2(); break; case Strategy3: pStrategy=new ConcreteStrategy3(); break; default: break; } }; ~ context(){delete pStrategy;}; virtual void ContextInterface(){ if (pStrategy) pStrategy->alogrithmInterface(); }; private: Strategy* pStrategy; /* data */ }; //策略基类 class Strategy { public: Strategy(); ~Strategy(); virtual void alogrithmInterface()=0; /* data */ }; //具体策略1 class ConcreteStrategy1:Strategy { public: ConcreteStrategy1(); ~ConcreteStrategy1(); void alogrithmInterface() { cout<<"Im ConcreteStrategy1!" } /* data */ }; //具体策略2 class ConcreteStrategy2:Strategy { public: ConcreteStrategy2(); ~ConcreteStrategy2(); void alogrithmInterface() { cout<<"Im ConcreteStrategy2!" } /* data */ }; //具体策略3 class ConcreteStrategy3:Strategy { public: ConcreteStrategy3(); ~ConcreteStrategy3(); void alogrithmInterface() { cout<<"Im ConcreteStrategy3!" } /* data */ }; int main(int argc, char const *argv[]) { context* cont=new context(Strategy1); cont->ContextInterface(); delete cont; cont=NULL; cont=new context(Strategy2); cont->ContextInterface(); delete cont; cont=NULL; cont=new context(Strategy3); cont->ContextInterface(); delete cont; cont=NULL; return 0; }
原文地址:http://blog.csdn.net/liucimin/article/details/39673427