用java实现:编程实现运算类一工厂设计模式【问题描述】 (1)定义抽象类 Operation ,有 double 型数据成员 numberA 、 numberB ,有抽象方法 getResult )(2)定义 Operation 的4个子类,分别实现加、减、除运算,二个数的平均数运算 (3)定义类 OperationFactory :有静态方法 Operation createOperate ( String operate );根据形参 operate 的值创建相应加、减、除、平均值类的对象,赋给抽象类引用后返回 (4)定义测试类及主方法:用户从键盘输入运算数及运算符,根据运算符调用 OperationFactory 类的静态方法,创建相应实例,设置运算数,输出运行结果
时间: 2023-12-10 22:37:28 浏览: 267
以下是用 Java 实现的代码:
```
// Operation.java
public abstract class Operation {
protected double numberA;
protected double numberB;
public Operation(double numberA, double numberB) {
this.numberA = numberA;
this.numberB = numberB;
}
public abstract double getResult();
}
// AddOperation.java
public class AddOperation extends Operation {
public AddOperation(double numberA, double numberB) {
super(numberA, numberB);
}
public double getResult() {
return numberA + numberB;
}
}
// SubtractOperation.java
public class SubtractOperation extends Operation {
public SubtractOperation(double numberA, double numberB) {
super(numberA, numberB);
}
public double getResult() {
return numberA - numberB;
}
}
// DivideOperation.java
public class DivideOperation extends Operation {
public DivideOperation(double numberA, double numberB) {
super(numberA, numberB);
}
public double getResult() {
if (numberB == 0) {
throw new IllegalArgumentException("Divide by zero");
}
return numberA / numberB;
}
}
// AverageOperation.java
public class AverageOperation extends Operation {
public AverageOperation(double numberA, double numberB) {
super(numberA, numberB);
}
public double getResult() {
return (numberA + numberB) / 2;
}
}
// OperationFactory.java
public class OperationFactory {
public static Operation createOperate(String operate, double numberA, double numberB) {
switch (operate) {
case "+":
return new AddOperation(numberA, numberB);
case "-":
return new SubtractOperation(numberA, numberB);
case "/":
return new DivideOperation(numberA, numberB);
case "avg":
return new AverageOperation(numberA, numberB);
default:
throw new IllegalArgumentException("Invalid operator: " + operate);
}
}
}
// Test.java
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number A: ");
double numberA = scanner.nextDouble();
System.out.print("Enter number B: ");
double numberB = scanner.nextDouble();
System.out.print("Enter operator (+, -, /, avg): ");
String operator = scanner.next();
Operation operation = OperationFactory.createOperate(operator, numberA, numberB);
double result = operation.getResult();
System.out.println("Result: " + result);
}
}
```
运行结果:
```
Enter number A: 5
Enter number B: 3
Enter operator (+, -, /, avg): avg
Result: 4.0
```
阅读全文