1、公共接口:方法由子类实现
2、加减乘除4个类分别实现接口中的计算结果的public int getResult(int num1, int num2)方法
3、简单工厂类以父类引用指向子类对象的方式返回子类对象
4、测试类中根据具体类的对象调用计算结果的方法并返回
package 创建型模式.工厂模式.简单工厂模式;
/**
* @Author: lxpStu
* @Date: 2021/10/25/0:10
* @Description:返回计算结果
*/
public interface Operation {
/**
* 返回计算结果
*
* @param num1
* @param num2
* @return
*/
double getResult(double num1, double num2);
}
package 创建型模式.工厂模式.简单工厂模式;
/**
* @Author: lxpStu
* @Date: 2021/10/25/0:09
* @Description:运算方法对象的对象工厂
*/
public class OperationFactory {
public static Operation createBean(String operation){
Operation opt = null;
switch (operation){
case "+" :
opt = new Add();
break;
case "-" :
opt = new Sub();
break;
case "*" :
opt = new Mul();
break;
case "/" :
opt = new Div();
break;
default:
}
return opt;
}
}
package 创建型模式.工厂模式.简单工厂模式;
/**
* @Author: lxpStu
* @Date: 2021/10/25/0:11
* @Description: 加法
*/
public class Add implements Operation {
@Override
public double getResult(double num1, double num2) {
return num1 + num2;
}
}
package 创建型模式.工厂模式.简单工厂模式;
/**
* @Author: lxpStu
* @Date: 2021/10/25/0:13
* @Description:减法
*/
public class Sub implements Operation {
@Override
public double getResult(double num1, double num2){
return num1 - num2;
}
}
package 创建型模式.工厂模式.简单工厂模式;
/**
* @Author: lxpStu
* @Date: 2021/10/25/0:14
* @Description:乘法
*/
public class Mul implements Operation {
@Override
public double getResult(double num1, double num2) {
return num1 * num2;
}
}
package 创建型模式.工厂模式.简单工厂模式;
/**
* @Author: lxpStu
* @Date: 2021/10/25/0:14
* @Description:除法
*/
public class Div implements Operation {
@Override
public double getResult(double num1, double num2) {
double res = 0;
try {
res = num1 / num2;
} catch (ArithmeticException e) {
e.printStackTrace();
System.out.println("除数不能为0");
}
return res;
}
}
package 创建型模式.工厂模式.简单工厂模式;
/**
* @Author: lxpStu
* @Date: 2021/10/25/0:21
* @Description:测试类
*/
public class Main {
public static void main(String[] args) {
Operation opt1 = OperationFactory.createBean("+");
System.out.println(opt1.getResult(1, 2));
Operation opt2 = OperationFactory.createBean("-");
System.out.println(opt2.getResult(2, 1));
Operation opt3 = OperationFactory.createBean("*");
System.out.println(opt3.getResult(4, 2));
Operation opt4 = OperationFactory.createBean("/");
System.out.println(opt4.getResult(8, 0));
}
}