java设计并实现符合单一职责原则、里氏替换原则、组合复用原则的计算器演示系统代码
时间: 2024-01-31 15:04:19 浏览: 54
举例解析Java的设计模式编程中里氏替换原则的意义
非常感谢您对设计模式的关注!以下是一个实现了单一职责、里氏替换、组合复用原则的计算器演示系统代码示例:
```
import java.util.Scanner;
interface Operation {
double getResult(double num1, double num2);
}
class Add implements Operation {
@Override
public double getResult(double num1, double num2) {
return num1 + num2;
}
}
class Subtract implements Operation {
@Override
public double getResult(double num1, double num2) {
return num1 - num2;
}
}
class Multiply implements Operation {
@Override
public double getResult(double num1, double num2) {
return num1 * num2;
}
}
class Divide implements Operation {
@Override
public double getResult(double num1, double num2) {
return num1 / num2;
}
}
class Calculator {
private Operation operation;
public void setOperation(Operation operation) {
this.operation = operation;
}
public double getResult(double num1, double num2) {
return operation.getResult(num1, num2);
}
}
public class Demo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double num1, num2;
System.out.println("Please enter two numbers:");
num1 = scanner.nextDouble();
num2 = scanner.nextDouble();
Calculator calculator = new Calculator();
System.out.println("Please select the operation you want to perform:");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
int choice = scanner.nextInt();
switch (choice) {
case 1:
calculator.setOperation(new Add());
break;
case 2:
calculator.setOperation(new Subtract());
break;
case 3:
calculator.setOperation(new Multiply());
break;
case 4:
calculator.setOperation(new Divide());
break;
default:
System.out.println("Invalid choice!");
return;
}
double result = calculator.getResult(num1, num2);
System.out.println("Result: " + result);
}
}
```
希望代码能够帮助您理解设计模式的实际应用。还有什么问题可以随时向我提出哦!
阅读全文