设计模式(C++) 练习2 工厂方法模式

设计模式(C++) 练习2 工厂方法模式

Design Patterns(C++) Exercise 2: Factory Model

Exercise 2

采用工厂方法重新设计计算器软件。 采用工厂方法,每一种运算都是一种具体的产品都需要为其设计一个具体的工厂。 要求画出类图。
2-1-Factory-Operator.png

/** 
 *  @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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值