书中笔记:1。代码规范性问题。2。复用性需提高。 3。封装代码,解耦合。
OperationFactory.java
package com
.chenny
.test
;
public class OperationFactory {
public static Operation
createOperate(String operate
) {
Operation operation
= null
;
switch (operate
) {
case "+":
operation
= new OperationAdd();
break;
case "-":
operation
= new OperationSub();
break;
case "*":
operation
= new OperationMul();
break;
case "/":
operation
= new OperationDiv();
break;
default:
throw new RuntimeException("不支持运算!");
}
return operation
;
}
}
Operation.java
package com
.chenny
.test
;
public abstract class Operation {
public double numberA
= 0;
public double numberB
= 0;
public abstract double getResult();
}
class OperationAdd extends Operation {
@Override
public double getResult() {
return numberA
+ numberB
;
}
}
class OperationSub extends Operation {
@Override
public double getResult() {
return numberA
- numberB
;
}
}
class OperationMul extends Operation {
@Override
public double getResult() {
return numberA
* numberB
;
}
}
class OperationDiv extends Operation {
@Override
public double getResult() {
if (numberB
== 0) {
throw new RuntimeException("除数不能为0!");
}
return numberA
/ numberB
;
}
}
Calculator.java
package com
.chenny
.test
;
import java
.util
.Scanner
;
public class Calculator {
public static void main(String
[] args
) {
Operation operation
= null
;
Scanner sc
= null
;
try {
sc
= new Scanner(System
.in
);
System
.out
.println("请选择要进行运算的样式(+、-、*、/)");
String symbol
= sc
.next();
operation
= OperationFactory
.createOperate(symbol
);
System
.out
.println("请输入数字A");
operation
.numberA
= sc
.nextDouble();
System
.out
.println("请输入数字B");
operation
.numberB
= sc
.nextDouble();
double result
= operation
.getResult();
System
.out
.println("计算结果为:" + result
);
}catch (Exception e
){
System
.out
.println("你输入的有误。");
}finally {
sc
.close();
}
}
}
转载请注明原文地址:https://tech.qufami.com/read-6443.html