核心理念
- 根据不同的参数返回不同的实例
- 专门用一个类来创建其它类的实例
- 创建的类都具用共同的父类
优缺点
优点
- 对象的创建和业务的处理分离开来,可以降低系统的耦合性
- 新增业务只需新增处理类即可,不影响原来的业务处理类
缺点
- 工厂类需要根据参数判断返回的类,与开闭原则有点相违背
代码示例
操作类
java
public abstract class Operation {
private double numberA;
private double numberB;
public double getNumberA() {
return numberA;
}
public void setNumberA(double numberA) {
this.numberA = numberA;
}
public double getNumberB() {
return numberB;
}
public void setNumberB(double numberB) {
this.numberB = numberB;
}
public abstract double getResult();
}
简单工厂类
java
public class OperationFactory {
public Operation createOperate(String operate){
if("+".equals(operate)){
return new AddOperation();
} else if("-".equals(operate)){
return new SubOperation();
}else{
return null;
}
}
}
加法运算类
java
public class AddOperation extends Operation {
@Override
public double getResult() {
return getNumberA() + getNumberB();
}
}
减法运算类
java
public class SubOperation extends Operation {
@Override
public double getResult() {
return getNumberA() - getNumberB();
}
}
测试
java
public class AppRun {
public static void main(String[] args) {
OperationFactory operationFactory = new OperationFactory();
Operation operate = operationFactory.createOperate("+");
operate.setNumberA(1.2);
operate.setNumberB(33.3);
System.out.println(operate.getResult());
}
}