简单工厂模式
专门定义一个类来创建其他类,继承该类的各个类产生不同实例对象
- 特点:简单工厂类根据对象传入的不同参数,实例化得到所需要的实例
//父类
public class Operation {
double numberA;
double numberB;
public void setNumberA(double numberA) {
this.numberA = numberA;
}
public void setNumberB(double numberB) {
this.numberB = numberB;
}
public double getResult() throws Exception {
return (double) 0;
}
}
//子类
public class OperationAdd extends Operation {
@Override
public double getResult() {
return numberA + numberB;
}
}
//简单工厂类
public class OperationFactory {
public static Operation createOperate(String operate){
Operation operation = null;
switch (operate){
case "+":
operation = new OperationAdd();
break;
case "-":
operation = new OperationSub();
break;
default:
break;
}
return operation;
}