简单工厂模式实现加减乘除法
1.创建运算的接口
public interface Operation { //提供计算两个数字的方法 double getResult(double num1,double num2); }
2.创建对应的加减乘除四个实现类
public class Addition implements Operation { //加法 @Override public double getResult(double num1, double num2) { return num1+num2; } }
public class Minus implements Operation { //减法 @Override public double getResult(double num1, double num2) { return num1-num2; } }
public class Multiplication implements Operation {//乘法 @Override public double getResult(double num1, double num2) { return num1*num2; } }
public class Division implements Operation {//除法 @Override public double getResult(double num1, double num2) { return num1/num2; } }
3.创建工厂类
public class OperationFactory { //计算机的工厂类 /* * 工厂模式 是我们最常用的实例化对象的模式! * 用工厂的方法替代new! * 虽然代码量没有减少 但是 提高了程序的扩展性! */ public static Operation getOperation(String o){ Operation operation=null; //多态 switch (o) { case "+": operation=new Addition(); break; case "-": operation=new Minus(); break; case "*": operation=new Multiplication(); break; case "/": operation=new Division(); break; } return operation; } }
4.创建测试类 运行 测试结果
public class FactoryTest { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("请输入第一个数字:"); double num1 = scanner.nextInt(); System.out.println("请输入运算符:"); String operation = scanner.next(); System.out.println("请输入第二个数字:"); double num2 = scanner.nextInt(); //创建运算的实例对象 Operation o = OperationFactory.getOperation(operation); //输出结果 System.out.println(o.getResult(num1, num2)); } }