标签:
现在可扩展性和可维护性特别强,即便是想要计算多个数,那也很容易了,改动的地方很少。而且还能防止恶意的程序员篡改代码。
如果需要进行两个以上的数字的运算,在该接口中添加方法就行了。
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); } }
源码下载:点我下载
java深入浅出设计模式----简单的工厂模式(一)----业务逻辑分离
标签:
原文地址:http://blog.csdn.net/escdelete/article/details/42711203