设计模式(C++) 练习2 工厂方法模式
Design Patterns(C++) Exercise 2: Factory Model
Exercise 2
采用工厂方法重新设计计算器软件。 采用工厂方法,每一种运算都是一种具体的产品都需要为其设计一个具体的工厂。 要求画出类图。
/**
* @author 墨晓柯
*/
#include <iostream>
#include <cmath>
#define interface class
using namespace std;
interface IOperator {
public:
virtual double getResult(double number1, double number2) = 0;
};
class AddOperator : public IOperator {
public:
double getResult(double number1, double number2) {
return (number1 + number2);
}
};
class SubOperator : public IOperator {
public:
double getResult(double number1, double number2) {
return (number1 - number2);
}
};
class MulOperator : public IOperator {
public:
double getResult(double number1, double number2) {
return (number1 * number2);
}
};
class DivOperator : public IOperator {
public:
double getResult(double number1, double number2) {
return (number1 / number2);
}
};
class ModOperator : public IOperator {
public:
double getResult(double number1, double number2) {
return fmod(number1, number2);
}
};
class OperatorFactory {
public:
static IOperator* createOperator(char operatorCode) {
switch(operatorCode) {
case '+': return new AddOperator();
case '-': return new SubOperator();
case '*': return new MulOperator();
case '/': return new DivOperator();
case '%': return new ModOperator();
default : return 0;
}
}
};
class Client {
public:
static void task() {
double number1 = 0;
cout << "number1 : ";
cin >> number1;
char operatorCode = 0;
cout << "operator: ";
cin >> operatorCode;
double number2 = 0;
cout << "number2 : ";
cin >> number2;
IOperator* aOperator = OperatorFactory::createOperator(operatorCode);
if(0 == aOperator) {
cout << "\nThe Operator Undefined!";
return;
}
double result = aOperator -> getResult(number1,number2);
cout << "--------------------------------\n";
cout << number1 << " " << operatorCode << " " << number2 << " = " << result << endl;
cout << "--------------------------------\n";
}
};
int main() {
Client::task();
return 0;
}