首页 > 解决方案 > 使用设计模式避免 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());
        
    }
}

标签: javadesign-patterns

解决方案


在这种情况下,不需要设计模式,但使用多态就足够了。更改 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
    }
}

推荐阅读