(1)简单工厂模式C++实现

本文通过一个计算器的例子介绍如何使用简单工厂模式来创建不同类型的运算操作。代码采用C++编写,展示了如何根据输入的运算符创建加法、减法、乘法和除法对象。

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

简单工厂模式C++实现

例子来源于《大话设计模式》第一章——实现一个计算器

#include<iostream>
#include<string>

using namespace std;

class albase {
    private:
        int A,B;
    public:
        virtual int getAns() {};
        void setA(int a) {
            A=a;
        }
        void setB(int b) {
            B=b;
        }
        int getA() {
            return A;
        }
        int getB() {
            return B;
        }
};

class add:public albase {
    public:
        int getAns() {
            return this->getA()+this->getB();
        }
};

class sub:public albase {
    public:
        int getAns() {
            return this->getA()-this->getB();
        }
};

class mul:public albase {
    public:
        int getAns() {
            //printf("here\n");
            return (this->getA())*(this->getB());
        }
};

class div:public albase {
    public:
        int getAns() {
            if(this->getB()==0) {
                //printf("分母不能为0\n");
                return 0;
            }
            return this->getA()/this->getB();
        }
};

class OF {
    public:
        albase* createOperate(char operate) {
            albase* oper;
            switch(operate) {
                case '+':
                    oper = new add();
                    break;
                case '-':
                    oper = new sub();
                    break;
                case '*':
                    oper = new mul();
                    break;
                case '/':
                    oper = new div();
                    break;
            }
            return oper;
        }
};

int main() {
    albase* algo;
    OF oper;
    algo=oper.createOperate('*');
    (*algo).setA(2);
    (*algo).setB(8);
    cout<<algo->getAns()<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值