java使用设计模式避免switchcase条件
我有几个代表算术运算的类(加号、减号、Pow…)在Java中,它们扩展了相同的抽象类Operator
,但它们在一个方法calculate
上有所不同
我试图找到一种避免切换情况的方法,以便使用设计模式(对设计模式来说是新的)以正确的方式实现这些类,但是我该怎么做呢?或者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());
}
}
# 1 楼答案
在这种情况下,不需要设计模式,但使用多态性就足够了。更改运算符类,如下所示:
然后用减号和加号类实现它:
这是测试的主要类: