看了<<大话设计模式>>, 照着写了一个简单工厂模式的计算器, 慢慢来, 不急.
#include <iostream>
#include <stdexcept>
using namespace std;
class Operation
{
public:
virtual float Operating() = 0;
public:
float numberleft;
float numberright;
};
class OperationAdd : public Operation
{
public:
float Operating()
{
return (numberleft + numberright);
}
};
class OperationSub : public Operation
{
public:
float Operating()
{
return (numberleft - numberright);
}
};
class OperationMul : public Operation
{
public:
float Operating()
{
return (numberleft * numberright);
}
};
class OperationDiv : public Operation
{
public:
float Operating()
{
if (numberright == 0) //抛出异常
throw std::out_of_range("参数异常: 除法右值不能为0");
return (numberleft / numberright);
}
};
// 运算符工厂
class OperationFactory
{
public:
OperationFactory()
{
op = NULL;
}
void Operating(float numberleft, char operate, float numberright)
{
switch(operate)
{
case ('+'):
op = new OperationAdd;
break;
case ('-'):
op = new OperationSub;
break;
case ('*'):
op = new OperationMul;
break;
case ('/'):
op = new OperationDiv;
break;
default:
throw std::out_of_range("参数异常: 没有输入正确的运算符");
break;
}
op->numberleft = numberleft;
op->numberright = numberright;
}
float GetResult()
{
return op->Operating();
}
private:
Operation * op;
};
void Operate()
{
float numberA;
float numberB;
char operate;
cout << "请输入数字A :";
cin >> numberA;
cout << "请输入运算符:";
cin >> operate;
cout << "请输入数字B :";
cin >> numberB;
OperationFactory *opef = new OperationFactory;
opef->Operating(numberA, operate, numberB);
cout << "结果是:" << opef->GetResult() << endl;
}
int main()
{
//Operate();
try
{
Operate();
}
catch (exception &e) // 异常要用引用收
{
cout << e.what() << endl;
}
catch (...)
{
}
system("pause");
return 0;
}