工厂方法模式(Factory Method),定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
用之前简单工厂模式做的计算器举例,先看简单工厂模式的实现:
// 运算类
public abstract class Operation {
protected int numberA;
protected int numberB;
protected abstract String getResult();
}
// 工厂类
public class OperFactory {
public static Operation createOper(String oper) {
Operation operation = null;
switch (oper) {
case "+":
operation = new Add();
break;
case "-":
operation = new Sub();
break;
case "*":
operation = new Mul();
break;
case "/":
operation = new Div();
break;
default:
break;
}
return operation;
}
}
// 加法运算类,减、乘法运算类似
public class Add extends Operation {
@Override
protected String getResult() {
return String.valueOf(numberA + numberB);
}
}
// 除法运算类类
public class Div extends Operation {
@Override
protected String getResult() {
return String.valueOf( numberB == 0 ? "除数不能为0" : (float)numberA / numberB);
}
}
工厂模式就是将之前的工厂类OperFactory
变为一个工厂接口,然后加减乘除各建一个具体工厂去实现这个接口:
public interface IFactory {
Operation createOperation();
}
public class AddFactory implements IFactory {
@Override
public Operation createOperation() {
return new Add();
}
}
public class DivFactory implements IFactory {
@Override
public Operation createOperation() {
return new Div();
}
}
下面来对比一下简单工厂模式和工厂模式的调用方法:
// 简单工厂模式
public class Calculate {
public static void main(String[] args) {
Operation oper = OperFactory.createOper("/");
oper.numberA = 7;
oper.numberB = 3;
System.out.println(oper.getResult());
}
}
// 工厂模式
public class Calculate {
public static void main(String[] args) {
IFactory operFactory = new DivFactory();
Operation operation = operFactory.createOperation();
operation.numberA = 7;
operation.numberB = 3;
System.out.println(operation.getResult());
}
}
可以看出来,如果需要增加其他的运算方法,使用简单工厂模式时,工厂类OperFactory
需要对原有的代码进行修改,就违背了开放-封闭原则。而采用工厂模式时,只需要增加一个新算法的工厂实现类,在调用时采用new NewOperationFactory()
就可以采用新的算法进行计算了。