通过一个计算器的例子来感受一下面向对象的三大特性
下面看一个计算器逻辑的实现:
public static void main(String[] args) {
try{
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第一个数字");
double numA = scanner.nextDouble();
System.out.println("请输入运算符(+-*/)");
String operate = scanner.next();
System.out.println("请输入第一个数字");
double numB = scanner.nextDouble();
String result = "";
switch (operate){
case "+":
result = String.valueOf(numA + numB);
break;
case "-":
result = String.valueOf(numA - numB);
break;
case "*":
result = String.valueOf(numA * numB);
break;
case "/":
if(numB != 0){
result = String.valueOf(numA / numB);
}else {
System.out.println("您输入的参数有误,除数不能为0");
}
break;
}
System.out.println("结果为:"+result);
}catch(Exception e){
System.out.println("您输入的参数有误");
}
}
乍一看没什么问题,该判断的逻辑也都判断了,也实现了一个简单计算器的基本功能,这样的编码方式是很直接的用计算机能够理解的逻辑来解决问题,这个逻辑本身没有错,但是这样的思维使得我们的程序只能满足当前的需求,程序不易维护、不易拓展、不易复用,这样的代码质量低、没有营养。
根据面向对象的三大特性来改造这段代码
-
封装
首先我们把计算机的业务逻辑封装起来,使得业务逻辑和界面逻辑分开
Operation类
public class Operation {
public Double getResult(double numberA,double numberB,String operate){
Double result = "";
switch (operate){
case "+":
result = numA + numB;
break;
case "-":
result = numA - numB;
break;
case "*":
result = numA * numB;
break;
case "/":
if(numB != 0){
result = numA / numB;
}else {
System.out.println("您输入的参数有误,除数不能为0");
}
break;
}
return result;
}
}```
**客户端类**
```java
public static void main(String[] args) {
try{
Operation operation = new Operation();
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第一个数字");
double numA = scanner.nextDouble();
System.out.println("请输入运算符(+-*/)");
String operate = scanner.next();
System.out.println("请输入第一个数字");
double numB = scanner.nextDouble();
double result = operation.getResult(numA,numB);
System.out.println("结果为:"+result);
}catch(Exception e){
System.out.println("您输入的参数有误");
}
}
- List item