代码实现:
#include<iostream> using namespace std; //策略基类 class COperation { public: int m_nFirst; int m_nSecond; virtual double GerResult() { double dResult=0; return dResult; } }; //策略具体类-加法类 class AddOperation:public COperation { public: AddOperation(int a,int b) { m_nFirst=a; m_nSecond=b; } virtual double GetResult() { return m_nFirst+m_nSecond; } }; class Context { private: COperation* op; public: Context(char cType) { switch(cType) { case'+': op=new AddOperation(3,8); break; default: op=new AddOperation(); break; } } double GetResult() { return op->GerResult(); } }; //客户端 int main() { int a,b; char c; cout<<"输入操作数吧,中间空格间隔:"<<endl; cin>>a>>b; Context* test=new Context('+'); cout<<test->GerResult()<<endl; return 0; }
原文地址:http://blog.csdn.net/u011421608/article/details/38873323