JAVA 3.编程实现运算类—工厂设计模式 【问题描述】 (1)定义抽象类Operation,有double型数据成员numberA、numberB,有抽象方法getResult() (2)定义Operation的4个子类,分别实现加、减、除运算,二个数的平均数运算 (3)定义类OperationFactory:有静态方法Operation createOperate(String operate); 根据形参operate的值创建相应加、减、除、平均值类的对象,赋给抽象类引用后返回 (4)定义测试类及主方法:用户从键盘输入运算数及运算符,根据运算符调用OperationFactory类的静态方法,创建相应实例,设置运算数,输出运行结果
时间: 2024-01-21 12:19:30 浏览: 70
以下是实现该问题的Java代码:
1. Operation.java
```
public 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();
}
```
2. AddOperation.java
```
public class AddOperation extends Operation {
@Override
public double getResult() {
return numberA + numberB;
}
}
```
3. SubtractOperation.java
```
public class SubtractOperation extends Operation {
@Override
public double getResult() {
return numberA - numberB;
}
}
```
4. DivideOperation.java
```
public class DivideOperation extends Operation {
@Override
public double getResult() {
if (numberB == 0) {
throw new IllegalArgumentException("除数不能为0");
}
return numberA / numberB;
}
}
```
5. AverageOperation.java
```
public class AverageOperation extends Operation {
@Override
public double getResult() {
return (numberA + numberB) / 2;
}
}
```
6. 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 MultiplyOperation();
break;
case "/":
operation = new DivideOperation();
break;
case "avg":
operation = new AverageOperation();
break;
default:
throw new IllegalArgumentException("不支持的运算符");
}
return operation;
}
}
```
7. Main.java
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入第一个数:");
double numberA = scanner.nextDouble();
System.out.print("请输入第二个数:");
double numberB = scanner.nextDouble();
System.out.print("请输入运算符(+、-、*、/、avg):");
String operate = scanner.next();
Operation operation = OperationFactory.createOperate(operate);
operation.setNumberA(numberA);
operation.setNumberB(numberB);
double result = operation.getResult();
System.out.println("运算结果为:" + result);
}
}
```
运行程序后,即可根据提示输入运算数和运算符,得到运算结果。
阅读全文