C++设计模式——简单工厂模式

简单工厂

通过封装,继承,多态把程序的耦合度降低,使得程序更加灵活,易于修改且易于重复。
考虑一个用单独的类来创造实例的过程,这就是工厂。
本模式通过编写计算器的方式来理解一段好的代码应该具有良好的可维护性和扩展性。通过抽象基类,子类继承基类的方式,实现可维护性和扩展性:
当后续添加其他计算方法时,只需新加一个子类来继承基类而无需修改已经实现的代码;当某种计算方式出现问题时,也只需查看该类的代码部分



 

 

 

#include<iostream>

using namespace std;

class Operation {
private:
    double _NumA;
    double _NumB;
public:
    void SetNumA() {
        cout << "Enter a double number: ";
        if (!(cin >> _NumA))
            throw "It must be a number!";
    }

    double GetNumA() {
        return _NumA;
    }

    void SetNumB() {
        cout << "Enter a double number: ";
        if (!(cin >> _NumB))
            throw "It must be a number!";
    }

    double GetNumB() {
        return _NumB;
    }

    virtual double GetResult() {
        int result = 0;
        return result;
    }
};

class OperationAdd :public Operation {
public:
    double GetResult() {
        double result = GetNumA() + GetNumB();
        return result;
    }
};

class OperationSub :public Operation {
public:
    double GetResult() {
        double result = GetNumA() - GetNumB();
        return result;
    }
};

class OperationMul :public Operation {
public:
    double GetResult() {
        double result = GetNumA() * GetNumB();
        return result;
    }
};

class OperationDiv : public Operation {
public:
    double GetResult() {
        if (GetNumB() == 0) {
            throw "The divisor cannot be 0";
        }
        double result = GetNumA() / GetNumB();
        return result;
    }
};

class OperatorFactory {
public:
    Operation* CreatOperation(char s) {
        Operation* ope = nullptr;
        switch (s)
        {
        case '+':
            ope = new OperationAdd;
            break;
        case '-':
            ope = new OperationSub;
            break;
        case '*':
            ope = new OperationMul;
            break;
        case '/':
            ope = new OperationDiv;
            break;
        default:
            throw "Error input operator!";
            break;
        }
        return ope;
    }

};

int main() {
    OperatorFactory fac;
    cout << "Choose an operation: ";
    char temp;
    cin >> temp;
    try {
        Operation* oper = fac.CreatOperation(temp);
        oper->SetNumA();
        oper->SetNumB();
        double result = 0;
        result = oper->GetResult();
        cout << "Result is: " << result << endl;
    }
    catch (const char* err) {
        cerr << err << endl;
        exit(EXIT_FAILURE);
    }
    return 0;
}

 

posted @ 2022-02-23 11:48  冰糖葫芦很乖  阅读(408)  评论(0编辑  收藏  举报