通过改造简单工厂模式计算器来简单梳理工厂方法模式
我们可以实现工厂方法模式,与前文简单工厂模式代码做个对比
工厂方法模式实现加减乘除计算器
定义相关类
首先定义一个工厂接口
//代理接口
public interface IFactory {
Operation CreateOperation();
}
分别定义加减乘除工厂类
public class AddFactory implements IFactory{
@Override
public Operation CreateOperation() {
return new OperationAdd();
}
}
public class SubFactory implements IFactory {
@Override
public Operation CreateOperation() {
return new OperationSub();
}
}
public class MulFactory implements IFactory {
@Override
public Operation CreateOperation() {
return new OperationMul();
}
}
public class DivFactory implements IFactory {
@Override
public Operation CreateOperation() {
return new OperationDiv();
}
}
运算符类及运算符具体类,同简单工厂模式中保持一致即可
public class Operation {
private double numA = 0;
private double numB = 0;
public double getNumA() {
return numA;
}
public void setNumA(double numA) {
this.numA = numA;
}
public double getNumB() {
return numB;
}
public void setNumB(double numB) {
this.numB = numB;
}
public double getResult() throws Exception {
double result = 0;
return result;
}
}
加法运算具体实现类
public class OperationAdd extends Operation{
@Override
public double getResult() {
double result = 0;
result = getNumA()+getNumB();
return result;
}
}
减法乘法除法同简单工厂模式一致,忽略。
定义业务方法
看在具体业务逻辑中如何使用
public class FactoryMethodTest {
public static void main(String[] args) {
//工厂方法模式
func1();
}
public static void func1(){
Scanner scanner = new Scanner(System.in);
System.out.println("请输入数字A:");
String strA = scanner.nextLine();
System.out.println("请输入运算符(+、-、*、/):");
String strOper = scanner.nextLine();
System.out.println("请输入数字B:");
String strB = scanner.nextLine();
String strResult = "";
try{
IFactory operFactory = null;
switch (strOper){
case "+":
operFactory = new AddFactory();
break;
case "-":
operFactory = new SubFactory();
break;
case "*":
operFactory = new MulFactory();
break;
case "/":
operFactory = new DivFactory();
break;
}
Operation oper = operFactory.CreateOperation();
oper.setNumA(Double.valueOf(strA));
oper.setNumB(Double.valueOf(strB));
strResult = oper.getResult()+"";
System.out.println("运算结果是:"+strResult);
}catch (Exception e){
System.out.println("运算出错,异常信息:"+e.getMessage());
}
}
}
执行结果
请输入数字A:
15
请输入运算符(+、-、*、/):
/
请输入数字B:
3
运算结果是:5.0
结果分析
工厂方法模式,定义一个用于创建对象的接口,让子类去决定实例化哪一个类。工厂方法模式,让一个类的实例化延迟到其子类上。
工厂方法模式克服了简单工厂模式违背开放封闭原则的缺点,又保持了封装对象创建的有点。
工厂方法模式是简单工厂模式的进一步抽象和推广。
https://xmlrambo.github.io/