设计模式(二)策略模式
单纯策略模式:
#include <iostream>
using namespace std;
//策略基类
class COperation{
public:
int m_iFirst;
int m_iSecond;
virtual double GetResult(){
double dResult = 0;
return dResult;
}
};
//策略具体类—加法类
class AddOperation : public COperation{
public:
AddOperation(int a, int b){
m_iFirst=a;
m_iSecond=b;
}
virtual double GetResult(){
return m_iFirst + m_iSecond;
}
};
class Context{
COperation *m_op;
public:
Context(COperation *temp){
m_op = temp;
}
double GetResult(){
return m_op->GetResult();
}
};
//客户端
int main(){
int a, b;
char c;
cin >> a >> b;
cout << "请输入运算符:";
cin >> c;
switch(c){
case '+':
Context *context = new Context(new AddOperation(a, b));
cout << context->GetResult() << endl;
break;
}
return 0;
}
策略模式跟工厂模式结合:
#include <iostream>
using namespace std;
class COperation{
public:
int m_nFirst;
int m_nSecond;
virtual double GetResult(){
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;
}
}
double GetResult(){
return op->GetResult();
}
};
//客户端
int main(){
Context *test=new Context('+');
cout<<test->GetResult()<<endl;
return 0;
}