代码实现
//simpleFactory.h
#ifndef _SimpleFactory_H_
#define _SimpleFactory_H_
#include <iostream>
#include <exception>
#include <string>
using namespace std;
class Operation {
protected:
double _numberA = 0;
double _numberB = 0;
public:
Operation() {}
Operation(double a, double b) {
_numberA = a;
_numberB = b;
}
Operation& operator=(Operation& p) {
_numberA = p.getNumberA();
_numberB = p.getNumberB();
}
double getNumberA() {
return _numberA;
}
void setNumberA(double value) {
_numberA = value;
}
double getNumberB() {
return _numberB;
}
void setNumberB(double value) {
_numberB = value;
}
virtual double GetResult() {
return 0;
}
};
class OperationAdd :public Operation {
double GetResult() {
double result = 0;
result = _numberA + _numberB;
return result;
}
};
class OperationSub :public Operation {
double GetResult() {
double result = 0;
result = _numberA - _numberB;
return result;
}
};
class OperationMul :public Operation {
double GetResult() {
double result = 0;
result = _numberA * _numberB;
return result;
}
};
class OperationDiv :public Operation {
double GetResult() {
double result = 0;
try {
result = _numberA / _numberB;
}
catch (exception&) {
cout << "发生除0异常" << endl;
}
return result;
}
};
class OperationFactory {
public:
static Operation* createOperation(char operate) {
Operation* oper;
switch (operate) {
case '+':
oper = new OperationAdd();
break;
case '-':
oper = new OperationSub();
break;
case '*':
oper = new OperationMul();
break;
case '/':
oper = new OperationDiv();
break;
}
return oper;
}
};
#endif //_SimpleFactory_H_
UML图
总结
可以发现,简单工厂类是制造运算类的对象的,并且只需要传递关键参数给简单工厂类的方法(通常为静态方法),就可以创造出相应的对象出来。
故简单工厂适用于工厂类负责创建的对象较少的场景,且客户端只需要传入工厂类的参数,对于如何创建对象不需要关心。
收获
1.可以通过封装、继承、多态把程序的耦合度降低。
2.可以通过设计模式使程序变得更加灵活,易于修改,并且易于复用。
3.简单工厂模式适用创建对象少的情况,需要传参来指定需要的对象(产品)。