如何实现一个简单的整数计算器呢? 一般想到的办法就是写一个方法,参数是两个整数和运算符号,根据不同的运算符号进行不同的运算。
public static void main(String[] args) { int a = 4; int b = 2; String oper = "/"; String result = deal(a, b, oper); System.out.println(a + oper + b + " = " + result); } public static String deal(int number1, int number2, String oper) { if ("+".equals(oper)) { return String.valueOf(number1 + number2); } else if ("-".equals(oper)) { return String.valueOf(number1 - number2); } else if ("*".equals(oper)) { return String.valueOf(number1 * number2); } else if ("/".equals(oper)) { if (number2 == 0) { return "除数不能为0"; } else { return String.valueOf(number1/number2); } } else { return "运算符号输入有误"; } }不过这样的代码不能很好的复用,而且如果需要新增算法时,需要在方法中增加一个if分支,如果运算逻辑处理出错,还会影响到之前的运算结果。
下面使用简单工厂模式,先确定需要的类:
运算基类,只需要两个属性和一个方法。其中两个属性为两个需要计算的数字,一个方法为获取结果的方法。运算工厂类,根据运算符选择相应的对象。各个运算的具体实现类。代码如下:
// 运算类 public abstract class Operation { protected int numberA; protected int numberB; protected abstract String getResult(); } // 工厂类 public class OperFactory { public static Operation createOper(String oper) { Operation operation = null; switch (oper) { case "+": operation = new Add(); break; case "-": operation = new Sub(); break; case "*": operation = new Mul(); break; case "/": operation = new Div(); break; default: break; } return operation; } } // 加法运算类,减、乘法运算类似 public class Add extends Operation { @Override protected String getResult() { return String.valueOf(numberA + numberB); } } // 除法运算类类 public class Div extends Operation { @Override protected String getResult() { return String.valueOf( numberB == 0 ? "除数不能为0" : (float)numberA / numberB); } } // 主程序 public class Calculate { public static void main(String[] args) { Operation oper = OperFactory.createOper("/"); oper.numberA = 7; oper.numberB = 3; System.out.println(oper.getResult()); } }运算结果为 2.3333333。 这就是一个简单工程模式的实现。