#include <iostream>
using namespace std;
//策略基类
class COperation
{
protected:
int m_nFirst;
int m_nSecond;
public:
virtual ~COperation(){}
virtual double GetResult() = 0;
};
//策略具体类—加法类
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 SubOperation : public COperation
{
public:
SubOperation(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(COperation* temp) :op(temp){}
void setStrategy(COperation* temp){
op = temp;
}
double GetResult(){
if (op != nullptr){
return op->GetResult();
}
}
};
//客户端
int main()
{
int a, b;
char ch;
cout << "输入运算数:a b \n";
cin >> a >> b;
cout << "输入运算符:\n";
cin >> ch;
Context* p = nullptr;
COperation* op = nullptr;
switch (ch)
{
case '+':
op = new AddOperation(a, b);
p = new Context(op);
cout << p->GetResult()<< endl;
break;
case '-':
break;
default:
break;
}
delete op;
delete p;
return 0;
}
策略模式
最新推荐文章于 2024-08-28 11:33:13 发布