现在可扩展性和可维护性特别强,即便是想要计算多个数,那也很容易了,改动的地方很少。而且还能防止恶意的程序员篡改代码。
如果需要进行两个以上的数字的运算,在该接口中添加方法就行了。
package separatetwo.operate; public interface Operate { public abstract int getResult(int numberOne, int numberTwo); }
加法
package separatetwo.operate; public class Add implements Operate { private Add() { }; private static Add addInstance = null; public static Add getAddInstance() { if (addInstance == null) { addInstance = new Add(); } return addInstance; } @Override public int getResult(int numberOne, int numberTwo) { return numberOne + numberTwo; } }
减法
package separatetwo.operate; public class Sub implements Operate { private Sub() { }; private static Sub subInstance = null; public static Sub getSubInstance() { if (subInstance == null) { subInstance = new Sub(); } return subInstance; } @Override public int getResult(int numberOne, int numberTwo) { return numberOne - numberTwo; } }
乘法
package separatetwo.operate; public class Mul implements Operate { private Mul() { }; private static Mul mulInstance = null; public static Mul getMulInstance() { return mulInstance == null ? new Mul() : mulInstance; } @Override public int getResult(int numberOne, int numberTwo) { return numberOne * numberTwo; } }
除法
package separatetwo.operate; public class Div implements Operate { private Div() { }; private static Div divInstance = null; public static Div getDivInstance() { return divInstance == null ? new Div() : divInstance; } @Override public int getResult(int numberOne, int numberTwo) { if(numberTwo != 0){ return numberOne / numberTwo; } return Integer.MIN_VALUE; } }
............随便来一个算法都可以实现了。
具体的用法:
package separatetwo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import separatetwo.operate.Div; public class ShowData { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); // 输入第一个数 System.out.println("请输入第一个数:"); String num1 = reader.readLine(); // 输入第二个数 System.out.println("请输入第二个数:"); String num2 = reader.readLine(); // 加法 // int result = Add.getAddInstance().getResult(Integer.valueOf(num1), Integer.valueOf(num2)); // System.out.print("计算结果是:"); // System.out.println(result); // 减法 // System.out.println(Sub.getSubInstance().getResult(Integer.valueOf(num1), Integer.valueOf(num2))); // 乘法 // System.out.println(Mul.getMulInstance().getResult(Integer.valueOf(num1), Integer.valueOf(num2))); // 除法 int result = Div.getDivInstance().getResult(Integer.valueOf(num1), Integer.valueOf(num2)); if(result == Integer.MIN_VALUE){ System.out.println("除数为0了"); } System.out.println(result); } }
源码下载:点我下载
时间: 2024-10-31 09:02:57