首先先看看用UML图画出的策略模式图 下面是实现 //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; }