大话设计模式笔记——工厂模式(C++计算器实现)

调试bug:基类里面的函数必须要定义或者定义为纯虚函数,否则会报链接错误。


工厂模式简单一点,就是调用一个函数,可以根据传入形参的不同可以生成不同的结果。

工厂模式基于多态,子类重写父类的虚函数(这个虚函数是做具体工作的函数),工厂制造的对象都隐式转换成基类对象,调用被重写的虚函数执行操作。


//
//  main.cpp
//  Factory
//
//  Created by Ben_22 on 14-5-28.
//  Copyright (c) 2014年 Ben_22. All rights reserved.
//

#include 
#include "string"
using namespace::std;


class Operation{
public:
    double _numberA = 0;
    double _numberB = 0;
public:
    virtual double getResult()=0;
};


class OperationAdd : public Operation{
public:
    double getResult() override{
        return _numberA+_numberB;
    }
};

class OperationSub : public Operation{
public:
    double getResult() override{
        return _numberA-_numberB;
    }
};

class OperationMul : public Operation{
public:
    double getResult() override{
        return _numberA*_numberB;
    }
};

class OperationDiv : public Operation{
public:
    double getResult() override{
        if (_numberB==0) {
            printf("异常\n");
            return 0;
        }
        return _numberA/_numberB;
    }
};

class OperationFactory{
public:
    static Operation* createOpr(char operate){
        Operation *oper = nullptr;
        switch (operate) {
            case '+':
                oper = new OperationAdd();
                break;
            case '-':
                oper = new OperationSub;
                break;
            case '*':
                oper = new OperationMul;
                break;
            case '\\':
                oper = new OperationDiv;
                break;
            default:
                break;
        }
        return oper;
    };
};

int main(int argc, const char * argv[])
{
    cout<<"输入第一个数字:"<>num1;
    cout<<"输入第一个数字:"<>num2;
    cout<<"输入操作运算符(+ - * \\):"<>opr;
    Operation *temp = OperationFactory::createOpr(opr);
    temp->_numberA = num1;
    temp->_numberB = num2;
    cout<getResult()<


你可能感兴趣的:(设计模式)