簡單工廠+策略模式實現簡易計算器

主函數之內也即客戶端界面程序(此處未實現界面)只使用了context一個類實現了封裝 

#include "operationFactory.h"

int main(int argc, char *argv[])
{
    //主函數之內也即客戶端界面程序(此處未實現界面)只使用了context一個類實現了封裝 
    OperationFactoryContext *context = new OperationFactoryContext();
    if (context->setInfo(10, '+', 20))
        cout << 10 << '+' << 20 << "=" << context->contextGetResult() << endl;
    delete context;
    return 0;
}

基類:Operation 使用虛析構函數否則delete時不會釋放派生類的資源,會報錯

派生類:OperationAdd OperationSub OperationMul OperationDiv 使用虛方法,實現簡單工廠模式

策略類:OperationFactoryContext 外部只操作這個類

#ifndef OPERATIONFACTORY
#define OPERATIONFACTORY

#include <iostream>
using namespace std;

class Operation
{
public:
    Operation():numA(0),numB(0){cout << "Operation" << endl;}
    virtual ~Operation(){cout << "~Operation" << endl;}

    double getnumA(){return numA;}
    double getnumB(){return numB;}

    void setnumA(int A){numA = A;}
    void setnumB(int B){numB = B;}

    double virtual getResult() = 0;

protected:
    double numA;
    double numB;
};

class OperationAdd : public Operation
{
public:
    OperationAdd(){cout << "OperationAdd" << endl;}
    ~OperationAdd(){cout << "~OperationAdd" << endl;}
    double getResult(){return (double)(numA+numB);}
};

class OperationSub : public Operation
{
public:
    OperationSub(){cout << "OperationSub" << endl;}
    ~OperationSub(){cout << "~OperationSub" << endl;}
    double getResult(){return double(numA-numB);}
};

class OperationMul : public Operation
{
public:
    OperationMul(){cout << "OperationMul" << endl;}
    ~OperationMul(){cout << "~OperationMul" << endl;}
    double getResult(){return (double)(numA*numB);}
};

class OperationDiv : public Operation
{
public:
    OperationDiv(){cout << "OperationDiv" << endl;}
    ~OperationDiv(){cout << "~OperationDiv" << endl;}
    double getResult(){return (double)(numA/numB);}
};

class OperationFactoryContext
{
public:
    OperationFactoryContext(){oper = NULL;}
    /* 動態聯編時delete基類的指針,需要基類有虛析構函數,不然會調到基類的析構函數而不調用派生類的 */
    ~OperationFactoryContext(){delete oper;}

    bool setInfo(double A, char operate, double B)
    {
        cout << "operate=" << operate << endl;
        switch(operate)
        {
            case '+':
                this->oper = new OperationAdd();break;
            case '-':
                this->oper = new OperationSub();break;
            case '*':
                this->oper = new OperationMul();break;
            case '/':
                this->oper = new OperationDiv();break;
            default:
                cout << "input operate " << operate << " error" << endl;
                return false;
        }
        oper->setnumA(A);
        oper->setnumB(B);
        return true;
    }
    double contextGetResult(){return oper->getResult();}

private:
    Operation *oper; 
};

#endif

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章