根据不同的需求派生不同子类,然后在工厂类中生成对应对象。
// 创建工厂
class AbstractCalculator{};
class AddCalculator : public AbstractCalculator{};
class SubCalculator : public AbstractCalculator{};
class MulCalculator : public AbstractCalculator{};
class DivCalculator : public AbstractCalculator{};
class OperatorFactory{
public:
AbstractCalculator* creatOperate(string str){
AbstractCalculator *oper = NULL;
if(str == "+"){
oper = new(AddCalculator);
}else if (str == "-"){
oper= new(SubCalculator);
}else if (str == "*"){
oper = new(MulCalculator);
}else if (str == "/"){
oper = new(DivCalculator);
}else{
cout << "false!!!!!" << endl;
}
return oper;
}
};
// 主函数
auto main() -> int {
AbstractCalculator *oper;
OperatorFactory factory;
oper = factory.creatOperate("+");
oper->m_Num1 = 1999;
oper->m_Num2 = 7234.44;
cout << oper->m_Num1 << " + " << oper->m_Num2 << " = " << oper->getResult() << endl;
return 0;
}