策略模式(Strategy):定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。[DP]
以下为策略模式的实现代码。
1 #include<iostream> 2 using namespace std; 3 4 class Strategy{ 5 public: 6 Strategy(void){} 7 virtual ~Strategy(void){} 8 9 virtual void AlgorithmInterface()=0; 10 }; 11 12 class ConcreteStrategyA:public Strategy{ 13 public: 14 void AlgorithmInterface(){ 15 cout<<"ConcreteStrategyA:AlgorithmInterface()"<<endl; 16 } 17 }; 18 19 class ConcreteStrategyB:public Strategy{ 20 public: 21 void AlgorithmInterface(){ 22 cout<<"ConcreteStrategyB:AlgorithmInterface()"<<endl; 23 } 24 }; 25 26 class Context{ 27 private: 28 Strategy* strategy; 29 public: 30 Context(Strategy* s):strategy(s){} 31 void setStrategy(Strategy* s){ 32 strategy=s; 33 } 34 void otherOperators(){ 35 cout<<"other operators"<<endl; 36 } 37 38 void execute(){ 39 if(strategy) 40 strategy->AlgorithmInterface(); 41 otherOperators(); 42 } 43 }; 44 45 int main() 46 { 47 ConcreteStrategyA strategyA; 48 ConcreteStrategyB strategyB; 49 Context context(&strategyA); 50 context.execute(); 51 context.setStrategy(&strategyB); 52 context.execute(); 53 54 return 0; 55 }