工厂模式:定义了一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类。
工厂方法模式:是简单工厂模式的衍生,解决了许多简单工厂模式的问题。首先完全实现‘开放-封闭 原则’,实现了可扩展。其次更复杂的层次结构,可以应用于产品结果复杂的场合。
利用工厂模式实现四则远算:
#include <iostream>
#include <string>
using namespace std;
class Operation
{
public:
Operation(){}
Operation(double a,double b):_numberA(a),_numberB(b){}
double getNumberA()
{
return _numberA;
}
void setNumberA(double a)
{
_numberA = a;
}
double getNumberB()
{
return _numberB;
}
void setNumberB(double b)
{
_numberB = b;
}
virtual double getResult() = 0;
private:
double _numberA;
double _numberB;
};
class OperationAdd : public Operation
{
public:
OperationAdd(){}
OperationAdd(double a,double b):Operation(a,b){}
double getResult()
{
double result = 0;
result = getNumberA() + getNumberB();
return result;
}
};
class OperationSub : public Operation
{
public:
OperationSub(){}
OperationSub(double a,double b):Operation(a,b){}
double getResult()
{
double result = 0;
result = getNumberA() - getNumberB();
return result;
}
};
class OperationMul : public Operation
{
public:
OperationMul(){}
OperationMul(double a,double b):Operation(a,b){}
double getResult()
{
double result = 0;
result = getNumberA() * getNumberB();
return result;
}
};
class OperationDiv : public Operation
{
public:
OperationDiv(){}
OperationDiv(double a,double b):Operation(a,b){}
double getResult()
{
double result = 0;
if(getNumberB() != 0)
{
result = getNumberA() / getNumberB();
return result;
}
else
return -12E24;
}
};
class IFactory
{
public:
virtual Operation* CreateOperation() = 0;
};
class AddFactory : public IFactory
{
public:
Operation* CreateOperation()
{
return new OperationAdd();
}
};
class SubFactory : public IFactory
{
public:
Operation* CreateOperation()
{
return new OperationSub();
}
};
class MulFactory : public IFactory
{
public:
Operation* CreateOperation()
{
return new OperationMul();
}
};
class DivFactory : public IFactory
{
public:
Operation* CreateOperation()
{
return new OperationDiv();
}
};
int main()
{
double numberA,numberB,result = 0;
cout << "请输入数字:";
cin >> numberA;
cout << "请输入数字:";
cin >> numberB;
cout << "得到的结果:";
IFactory* operFactory = new DivFactory();
Operation* oper = operFactory->CreateOperation();
oper->setNumberA(numberA);
oper->setNumberB(numberB);
result = oper->getResult();
if(result = -12E24)
cout << "您输入有误,请正确输入。";
else
cout << result << endl;
return 0;
}