1. 定义
工厂方法模式(Factory Method),定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
2. 工厂方法模式结构图
3. 工厂方法模式的基本代码
运算类Operation
public class Operation {
private double numberA=0;
private double numberB=0;
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 double getResult(){
return 0;
}
}
加法运算类OperationAdd,继承自Operation
public class OperationAdd extends Operation {
@Override
public double getResult() {
double result = 0;
result = getNumberA() + getNumberB();
return result;
}
}
减法运算类OperationSub
public class OperationSub extends Operation {
@Override
public double getResult() {
double result = 0;
result = getNumberA() - getNumberB();
return result;
}
}
工厂类
public interface Factory {
public Operation createOperation();
}
加法工厂类和减法工厂类
public class AddFactory implements Factory {
@Override
public Operation createOperation() {
return new OperationAdd();
}
}
public class SubFactory implements Factory {
@Override
public Operation createOperation() {
return new OperationSub();
}
}
客户端调用代码
public static void main(String[] args) {
Factory factory = new AddFactory();
Operation operation = factory.createOperation();
operation.setNumberA(5);
operation.setNumberB(3);
double result = operation.getResult();
System.out.println(result);
}
4. 工厂方法模式与简单工厂模式的区别
简单工厂模式如果要增加一个乘法,那么就要修改工厂类,增加条件判断,这违背了开放—封闭原则(对扩展开发,对修改关闭)。而工厂方法模式增加乘法工厂和乘法运算类就可以,并没有修改到原有的类,符合开放—封闭原则。