策略模式的C++实现

首先先看看用UML图画出的策略模式图

策略模式的C++实现_第1张图片

下面是实现

//strategy.h #ifndef AFX_CLASS_STRATEGY #define AFX_CLASS_STRATEGY class Strategy { public: virtual void AlgorithmInterface() { cout<<"无调用算法"<<endl; } }; #endif #ifndef AFX_CONCRETESTRATEGY #define AFX_CONCRETESTRATEGY //算法A class ConcreteStrategyA:public Strategy { public: virtual void AlgorithmInterface() { cout<<"算法A实现"<<endl; } }; //算法B class ConcreteStrategyB:public Strategy { public: virtual void AlgorithmInterface() { cout<<"算法B的实现"<<endl; } }; //算法C class ConcreteStrategyC:public Strategy { public: virtual void AlgorithmInterface() { cout<<"算法C的实现"<<endl; } }; #endif #ifndef AFX_CLASS_CONTEXT #define AFX_CLASS_CONTEXT class Context { public: Context(Strategy *strategy) { this->strategy = strategy; } void ContextInterface() { strategy->AlgorithmInterface(); } private: Strategy *strategy; }; #endif

 

主函数调用:

// main.cpp #include <iostream> #include <string> #include <conio.h> using namespace std; #include "strategy.h" int main(int argc,char *argv[]) { Context *context = NULL; context=new Context( new ConcreteStrategyA() ); context->ContextInterface(); context=new Context( new ConcreteStrategyB() ); context->ContextInterface(); context=new Context( new ConcreteStrategyC() ); context->ContextInterface(); getch(); return 1; }

你可能感兴趣的:(C++,c,算法,Class,UML)