3.编程实现运算类—工厂设计模式 【问题描述】 (1)定义抽象类Operation,有double型数据成员numberA、numberB,有抽象方法getResult() (2)定义Operation的4个子类,分别实现加、减、除运算,二个数的平均数运算 (3)定义类OperationFactory:有静态方法Operation createOperate(String operate); 根据形参operate的值创建相应加、减、除、平均值类的对象,赋给抽象类引用后返回 (4)定义测试类及主方法:用户从键盘输入运算数及运算符,根据运算符调用OperationFactory类的静态方法,创建相应实例,设置运算数,输出运行结果 【输入形式】 一个表达式(数据与运算符之间空格间隔) 【输出形式】 表达式运算的结果,保留3位小数 【样例输入】 表4.3实验题目3测试用例 序号 样例输入 样例输出 1 45.8 + 80.9 Result:126.700 2 100 / 3 Result:33.333 3 123 / 0 Devide by zero!
时间: 2024-01-22 20:21:25 浏览: 183
抽象类Operation的代码实现:
```java
abstract class Operation {
protected double numberA;
protected double numberB;
public void setNumberA(double numberA) {
this.numberA = numberA;
}
public void setNumberB(double numberB) {
this.numberB = numberB;
}
public abstract double getResult();
}
```
加、减、除、平均值类的代码实现:
```java
class AddOperation extends Operation {
@Override
public double getResult() {
return numberA + numberB;
}
}
class SubtractOperation extends Operation {
@Override
public double getResult() {
return numberA - numberB;
}
}
class DivideOperation extends Operation {
@Override
public double getResult() {
if (numberB == 0) {
throw new IllegalArgumentException("Devide by zero!");
}
return numberA / numberB;
}
}
class AverageOperation extends Operation {
@Override
public double getResult() {
return (numberA + numberB) / 2;
}
}
```
OperationFactory类的代码实现:
```java
public class OperationFactory {
public static Operation createOperate(String operate) {
Operation operation = null;
switch (operate) {
case "+":
operation = new AddOperation();
break;
case "-":
operation = new SubtractOperation();
break;
case "/":
operation = new DivideOperation();
break;
case "avg":
operation = new AverageOperation();
break;
}
return operation;
}
}
```
测试类及主方法的代码实现:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double a = scanner.nextDouble();
String operate = scanner.next();
double b = scanner.nextDouble();
Operation operation = OperationFactory.createOperate(operate);
operation.setNumberA(a);
operation.setNumberB(b);
try {
double result = operation.getResult();
System.out.printf("Result:%.3f", result);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
```
这里的实现使用了工厂模式,根据输入的运算符创建相应的运算类对象,然后设置运算数并计算结果。如果是除法运算时,如果除数为0则会抛出IllegalArgumentException异常。输出结果时保留3位小数。
阅读全文