【设计模式】——简单工厂模式

  简单工厂模式没有抽象类,只有一个具体工厂类,所有产品的生产都由这个工厂类的对象来负责,如果这个工厂类中生产产品的方法被声明为静态的,那么连这个工厂对象也不是必须的了,直接使用工厂类名就可以调用生产方法。生产方法被声明为静态的,所以简单工厂模式也叫静态工厂模式。简单工厂模式并不是一个好的设计模式,因为它不符合开闭原则。

【设计模式】——简单工厂模式_第1张图片

 

#include 
using namespace std;
class Operation
{
private:
    double _numberA;
    double _numberB;
public:
    Operation(){}
    Operation(double numA,double numB):_numberA(numA),_numberB(numB){}
    void set_numberA(double numA)
    {
        _numberA=numA;
    }
    double get_numberA()
    {
        return _numberA;
    }
    void set_numberB(double numB)
    {
        _numberB=numB;
    }
    double get_numberB()
    {
        return _numberB;
    }
    virtual double GetResult()
    {
        double result=0;
        return result;
    }
};
//加减乘除类
class OperationAdd:public Operation
{
public:
    OperationAdd(){}
    OperationAdd(double numA,double numB):Operation(numA,numB){}
    double GetResult()
    {
        double result=0;
        result=get_numberA()+get_numberB();
        return result;
    }
};
class OperationSub:public Operation
{
public:
    OperationSub(){}
    OperationSub(double numA,double numB):Operation(numA,numB){}
    double GetResult()
    {
        double result=0;
        result=get_numberA()-get_numberB();
        return result;
    }
};
class OperationMul:public Operation
{
public:
    OperationMul(){}
    OperationMul(double numA,double numB):Operation(numA,numB){}
    double GetResult()
    {
        double result=0;
        result=get_numberA()*get_numberB();
        return result;
    }
};
class OperationDiv:public Operation
{
public:
    OperationDiv(){}
    OperationDiv(double numA,double numB):Operation(numA,numB){}
    double GetResult()
    {
        double result=0;
        if(get_numberB()==0)
        {
            cout << "除数不能为0" << endl;
            return -1;
        }
        result=get_numberA()/get_numberB();
        return result;
    }
};
//简单运算工厂类
class OperationFactory
{
public:
    Operation *CreateOperate(char operate)
    {
        Operation *oper=NULL;
        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()
{
    Operation *oper;
    OperationFactory operFactory;
    oper=operFactory.CreateOperate('+');
    oper->set_numberA(1);
    oper->set_numberB(2);
    double result=oper->GetResult();
    cout << "result=" << result << endl;
    return 0;
}

 

转载于:https://www.cnblogs.com/awy-blog/p/3795592.html

你可能感兴趣的:(【设计模式】——简单工厂模式)