用簡單工廠設計模式寫加減乘除運算

#include <iostream>
#include <string>

using namespace std;

class Operator
{
public:
    void set(int a, int b)
    {
        this->m_a = a;
        this->m_b = b;
    }

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

protected:
    int m_a;
    int m_b;
};

class operatorAdd:public Operator
{
public:
    int result()//int a, int b,
    {
        int result = 0;
        result = m_a + m_b;
        return result;
    }
};

class operatorSub:public Operator
{
public:
    int result()//int a, int b,
    {
        int result = 0;
        result = m_a - m_b;
        return result;
    }
};

class operatorMul:public Operator
{
public:
    int result()//int a, int b,
    {
        int result = 0;
        result = m_a * m_b;
        return result;
    }
};

class operatorDiv:public Operator
{
public:
    int result()//int a, int b,
    {
        int result = 0;
        result = m_a / m_b;
        return result;
    }
};

class OperatorFactory// 核心工廠,用來生產對象
{
public:
    Operator* createoperator(char s)
    {
        Operator* ope = nullptr;
        switch(s)
        {
        case '+':
            ope = new operatorAdd;
            break;
        case '-':
            ope = new operatorSub;
            break;
        case'*':
            ope = new operatorMul;
            break;
        case '/':
            ope = new operatorDiv;
            break;
        default:
            break;
        }
        return ope;
    }
};

int main(int argc, char *argv[])
{
    Operator *p = nullptr;

    OperatorFactory p1 ;//= new OperatorFactory;

    p = p1.createoperator('/');

    p->set(1,2);

    int ret = p->result();

    cout << ret << endl;

    return 0;
}

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