1 概述
将创造对象的工作交给一个单独的类来实现 ,这个单独的类就是工厂。
2 实现
假设要做一个计算器的需求,通常我们想到的是这样写:
java
package com.example.easyfactory;
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
try {
Scanner sc =new Scanner(System.in);
System.out.println("请输入数字A:");
double numberA = Double.parseDouble(sc.nextLine());
System.out.println("请输入运算符(+、-、*、/):");
String strOperate = sc.nextLine();
System.out.println("请输入数字B:");
double numberB = Double.parseDouble(sc.nextLine());
double result = 0d;
switch (strOperate) {
case "+":
result = numberA + numberB;
break;
case "-":
result = numberA - numberB;
break;
case "*":
result = numberA * numberB;
break;
case "/":
result = numberA / numberB;
break;
}
System.out.println("结果是:" + result);
}catch (Exception e) {
System.out.println("输入有错");
}
}
}
但这段代码的问题在于,其一显示和业务逻辑没有分离,其二是没有使用面向对象的编程思想,可扩展性和可重用性都很差。
可以考虑使用简单工厂模式,将各个计算逻辑进行分离,成为单独的类,在工厂类中根据传入的参数构造不同预算符对象。
运算符抽象类:
java
public abstract class Operation {
public double getResult(double numberA, double numberB) {
return 0d;
}
}
接下来是四个具体的运算符类
java
public class Add extends Operation{
@Override
public double getResult(double numberA, double numberB) {
return numberA + numberB;
}
}
java
public class Sub extends Operation{
@Override
public double getResult(double numberA, double numberB) {
return numberA - numberB;
}
}
java
public class Mul extends Operation{
@Override
public double getResult(double numberA, double numberB) {
return numberA * numberB;
}
}
java
public class Div extends Operation {
@Override
public double getResult(double numberA, double numberB) {
if (numberB == 0) {
System.out.println("除数不能为0");
throw new ArithmeticException();
}
return numberA / numberB;
}
}
工厂类
java
public class OperationFactory {
public static Operation createOperation(String operate) {
Operation oper = null;
switch (operate) {
case "+":
oper = new Add();
break;
case "-":
oper = new Sub();
break;
case "*":
oper = new Mul();
break;
case "/":
oper = new Div();
break;
}
return oper;
}
}
测试类
java
public class Test {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
System.out.println("请输入数字A:");
double numberA = Double.parseDouble(sc.nextLine());
System.out.println("请输入运算符(+、-、*、/):");
String strOperate = sc.nextLine();
System.out.println("请输入数字B:");
double numberB = Double.parseDouble(sc.nextLine());
double result = 0d;
Operation oper = OperationFactory.createOperation(strOperate);
result = oper.getResult(numberA, numberB);
System.out.println("结果为:" + result);
}
}
根据传入的参数的不同,来从工厂类中获取具体的运算符类对象,并调用运算方法。
3 总结
简单工厂模式就是通过一个抽象类抽象出一个抽象类和一个公共操作方法。具体的操作类来继承抽象类,并重写该方法。工厂中根据传入参数的不同来构造具体的操作类对象,并赋值给其父类(即抽象类),实际运行时由于多态特性,会运行具体操作类中被重写的方法。