一、 定义
工厂方法模式(Factory Method),定义一个用于创建对象的接口,让子类决定实例化哪一个类,使一个类的实例化延迟到子类。
简单工厂模式中工厂类包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类。工厂方法模式中,客户端决定实例化哪一个工厂,这里相当于把简单工厂模式中在工厂类中的逻辑判断移到了客户端代码中判断。工厂方法模式克服了简单工厂模式中开放-封闭原则的不足。
二、 结构图
三、 示例代码(以简单工厂方法的计算器为例,使用工厂方法模式实现)
//运算基类
package org.example.FactoryMethod;
public class BaseOption {
private double numberA;
private double numberB;
private double dresult;
public double GetResult(){
return dresult;
}
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 void setDresult(double dresult) {
this.dresult = dresult;
}
}
//加法运算类
package org.example.FactoryMethod;
public class AddOption extends BaseOption {
private double addResult;
// AddOption(double numberA, double numberB){
// setNumberA(numberA);
// setNumberB(numberB);
// }
@Override
public void setDresult(double dresult) {
addResult = dresult;
}
@Override
public double GetResult() {
setDresult(getNumberA() + getNumberB());
return addResult;
}
}
//减法运算类
package org.example.FactoryMethod;
public class MinusOption extends BaseOption {
private double minusResult;
// MinusOption(double numberA, double numberB){
// setNumberA(numberA);
// setNumberB(numberB);
// }
@Override
public void setDresult(double dresult) {
minusResult = dresult;
}
@Override
public double GetResult() {
setDresult(getNumberA() - getNumberB());
return minusResult;
}
}
//加法工厂类
package org.example.FactoryMethod;
public class AddFactory implements IOptionFactory {
private BaseOption addOption = new AddOption();
@Override
public BaseOption GetOptionFactory() {
return addOption;
}
}
//减法工厂类
package org.example.FactoryMethod;
public class MinusFactory implements IOptionFactory {
private BaseOption baseOption = new MinusOption();
@Override
public BaseOption GetOptionFactory() {
return baseOption;
}
}
//抽象工厂类
package org.example.FactoryMethod;
public interface IOptionFactory {
BaseOption GetOptionFactory();
}
//测试类
package org.example.FactoryMethod;
import java.util.Arrays;
public class TestFactoryMethod {
public static void main(String[] args) {
IOptionFactory optionFactory = new AddFactory();
AddOption bo = (AddOption) optionFactory.GetOptionFactory();
bo.setNumberA(40);
bo.setNumberB(30);
System.out.println(bo.GetResult());
IOptionFactory minusFactory = new MinusFactory();
MinusOption mo = (MinusOption) minusFactory.GetOptionFactory();
mo.setNumberA(40);
mo.setNumberB(30);
System.out.println(mo.GetResult());
}
}