写一个简单的计算器
缺点:完全面向过程设计,缺少代码重用
加法运算
1 //加法运算,返回结果 2 public class AddOperation extends Operation { 3 4 public double getResult() { 5 double result = this.getNum1() + this.getNum2(); 6 return result; 7 } 8 }
减法运算
1 //减法运算 2 public class SubtractionOperation extends Operation { 3 4 public double getResult() { 5 double result = this.getNum1() - this.getNum2(); 6 return result; 7 } 8 }
运算类
1 //运算类 抽象类 2 public abstract class Operation { 3 private double num1; 4 private double num2; 5 6 public double getNum1() { 7 return num1; 8 } 9 10 public void setNum1(double num1) { 11 this.num1 = num1; 12 } 13 14 public double getNum2() { 15 return num2; 16 } 17 18 public void setNum2(double num2) { 19 this.num2 = num2; 20 } 21 22 public abstract double getResult(); 23 }
运算工厂接口
1 //运算工厂接口 2 public interface OperationFactory { 3 public Operation getOperation(); 4 }
主方法测试
1 import java.util.Scanner; 2 //主方法测试 3 public class MainClass { 4 public static void main(String[] args) { 5 //1.接受控制台输入 6 System.out.println("---计算器程序---"); 7 System.out.println("输入第一个操作数"); 8 Scanner scanner = new Scanner(System.in); 9 String strNum1 = scanner.nextLine(); 10 11 System.out.println("输入运算符"); 12 String oper = scanner.nextLine(); 13 14 System.out.println("输入第二个操作数"); 15 String strNum2 = scanner.nextLine(); 16 double result = 0; 17 double num1 = Double.parseDouble(strNum1); 18 double num2 = Double.parseDouble(strNum2); 19 20 //2.进行运算 21 if("+".equals(oper)) { 22 OperationFactory factory = new AddOperationFactory(); 23 Operation operation = factory.getOperation(); 24 operation.setNum1(num1); 25 operation.setNum2(num2); 26 result = operation.getResult(); 27 } 28 29 //3.返回结果 30 System.out.println(strNum1 + oper + strNum2 + "=" + result); 31 } 32 }