用简单工厂设计模式写加减乘除运算

本文介绍了一种使用C++实现的运算符工厂模式,通过继承和多态创建加、减、乘、除等运算符对象。核心部分包括定义一个抽象基类Operator,以及四个派生类分别实现加、减、乘、除操作。通过OperatorFactory类的createoperator方法,根据传入的字符参数创建相应的运算符对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值