java - 使用设计模式避免 switch-case 条件
问题描述
我有几个类代表Java中的算术运算(加号,减号,Pow ...),它们扩展了相同的抽象类Operator
,但它们在一种方法上有所不同 - calculate
。
我试图找到一种方法来避免 switch-case 条件,以便使用设计模式(设计模式的新手)以正确的方式实现这些类,但我该怎么做呢?还是 switch-case 语句是实现它的正确方法?
这是抽象类:
public abstract class Operator {
private int a, b;
public Operator(int a, int b){
this.a = a;
this.b = b;
}
public float calculate() {
// here I want to return the result depending on the operator. If Plus extends Operator then the returned value is this.a + this.b
}
public void print() {
System.out.println("This is the result : %f", this.calculate());
}
}
解决方案
在这种情况下,不需要设计模式,但使用多态就足够了。更改 Operator 类,如下所示:
public abstract class Operator {
protected int a;
protected int b;
public Operator(int a, int b){
this.a = a;
this.b = b;
}
public abstract float calculate();
public void print() {
System.out.println("This is the result : " + this.calculate());
}
}
然后用 Minus 和 Plus 类实现它:
public class Plus extends Operator{
public Plus(int a, int b) {
super(a, b);
}
@Override
public float calculate() {
return this.a + this.b;
}
}
public class Minus extends Operator{
public Minus(int a, int b) {
super(a, b);
}
@Override
public float calculate() {
return this.a - this.b;
}
}
这是用于测试的 Main 类:
public class Main {
public static void main(String[] args) {
Operator minus = new Minus(5,2);
minus.print(); // prints: This is the result : 3.0
Operator plus = new Plus(5,2);
plus.print(); // prints: This is the result : 7.0
}
}
推荐阅读
- koin - 如何在 koin-ktor 项目中自定义 NettyApplicationEngine?
- ios - 使用自定义间隔安排本地通知
- php - 尽管 Google PageSpeed “积极”,但加载时间却很长
- python - pandas date_range 中非工作日的频率别名
- android - 无法通过https访问网页
- flask - 无法从本地 python 文件导入模型
- javascript - 从 v-text-field Vue 中删除空格
- javascript - 如何在异步功能中获取更新的道具?
- java - 在 Angular 中的任何请求之前询问服务器 api
- php - “帐户登录不正确或您的帐户暂时被禁用。请稍候,稍后再试。”}