代码无错就是优? ——简单工厂模式(计算器)
作者:互联网
要求体现面向对象的思想
UML图:
Operation类
public class Operation {
static double numberA;
static double numberB;
public static double getNumberA() {
return numberA;
}
public static void setNumberA(double numberA) {
Operation.numberA = numberA;
}
public static double getNumberB() {
return numberB;
}
public static void setNumberB(double numberB) {
Operation.numberB = numberB;
}
public double getResult() {
double result = 0;
return result;
}
}
加法类
public class OperationAdd extends Operation{
public double getResult(){
double result = 0;
result = numberA + numberB;
return result;
}
}
减法类
public class OperationSub extends Operation{
public double getResult(){
double result = 0;
result = numberA - numberB;
return result;
}
}
乘法类
public class OperationMul extends Operation{
public double getResult(){
double result = 0;
result = numberA * numberB;
return result;
}
}
除法类
public class OperationDiv extends Operation{
public double getResult(){
double result = 0;
result = numberA / numberB;
return result;
}
}
简单运算工厂类
public class OperationFactory {
public static Operation createOperate(String operate){
Operation oper = null;
switch(operate){
case “+”:
oper = new OperationAdd();
break;
case “-”:
oper = new OperationSub();
break;
case “*”:
oper = new OperationMul();
break;
case “/”:
oper = new OperationDiv();
break;
}
return oper;
}
}
Main类
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("请输入数字A:");
double a = sc.nextDouble();
System.out.println("请输入运算符:");
String operator = sc.next();
System.out.println("请输入数字c:");
double c = sc.nextDouble();
Operation oper = OperationFactory.createOperate(operator);
oper.setNumberA(a);
oper.setNumberB(c);
System.out.println("结果:"+oper.getResult());
}
}
标签:oper,numberB,double,代码,result,计算器,Operation,无错,public 来源: https://blog.csdn.net/weixin_42487387/article/details/88399411