1.Strategy模式和Template模式要解决的问题是相同(类似)的,都是为了给业务逻辑(算法)具体实现和抽象接口之间的解耦。Strategy模式将逻辑(算法)封装到一个类(Context)里面,通过组合的方式将具体算法的实现在组合对象中实现,再通过委托的方式将抽象接口的实现委托给组合对象实现.
2.Strategy Pattern 结构图
3.实现
1 #ifndef _STRATEGY_H_ 2 #define _STRATEGY_H_ 3 4 class Strategy 5 { 6 public: 7 Strategy(); 8 virtual ~Strategy(); 9 virtual void AlgrithmInterface() = 0; 10 protected: 11 private: 12 }; 13 14 class ConcreteStrategyA:public Strategy 15 { 16 public: 17 ConcreteStrategyA(); 18 virtual ~ConcreteStrategyA(); 19 void AlgrithmInterface(); 20 protected: 21 private: 22 }; 23 24 class ConcreteStrategyB:public Strategy 25 { 26 public: 27 ConcreteStrategyB(); 28 virtual ~ConcreteStrategyB(); 29 void AlgrithmInterface(); 30 protected: 31 private: 32 }; 33 34 #endif
1 #include "Strategy.h" 2 #include <iostream> 3 using namespace std; 4 5 Strategy::Strategy() 6 { 7 8 } 9 Strategy::~Strategy() 10 { 11 cout<<"~Strategy....."<<endl; 12 } 13 void Strategy::AlgrithmInterface() 14 { 15 16 } 17 ConcreteStrategyA::ConcreteStrategyA() 18 { 19 20 } 21 ConcreteStrategyA::~ConcreteStrategyA() 22 { 23 cout<<"~ConcreteStrategyA....."<<endl; 24 } 25 void ConcreteStrategyA::AlgrithmInterface() 26 { 27 cout<<"test ConcreteStrategyA....."<<endl; 28 } 29 ConcreteStrategyB::ConcreteStrategyB() 30 { 31 32 } 33 ConcreteStrategyB::~ConcreteStrategyB() 34 { 35 cout<<"~ConcreteStrategyB....."<<endl; 36 } 37 void ConcreteStrategyB::AlgrithmInterface() 38 { 39 cout<<"test ConcreteStrategyB....."<<endl; 40 }
1 #ifndef _CONTEXT_H_ 2 #define _CONTEXT_H_ 3 4 class Strategy; 5 6 class Context 7 { 8 public: 9 Context(Strategy* stg); 10 ~Context(); 11 void DoAction(); 12 protected: 13 private: 14 Strategy* _stg; 15 }; 16 17 #endif
1 #include "Context.h" 2 #include "Strategy.h" 3 #include <iostream> 4 using namespace std; 5 6 Context::Context(Strategy* stg) 7 { 8 _stg = stg; 9 } 10 Context::~Context() 11 { 12 if (!_stg) delete _stg; 13 } 14 void Context::DoAction() 15 { 16 _stg->AlgrithmInterface(); 17 }
1 #include "Context.h" 2 #include "Strategy.h" 3 #include <iostream> 4 using namespace std; 5 6 int main(int argc,char* argv[]) 7 { 8 Strategy* ps = new ConcreteStrategyA(); 9 Context* pc = new Context(ps); 10 pc->DoAction(); 11 if (NULL != pc) 12 delete pc; 13 14 return 0; 15 }