实现方式一:
public enum Operation {
    PLUS, MINUS, TIMES, DIVIDE;

    double apply(double x, double y) {
        switch (this) {
            case PLUS:
                return x + y;
            case MINUS:
                return x - y;
            case TIMES:
                return x * y;
            case DIVIDE:
                return x / y;
        }
        throw new AssertionError("Unknow op:" + this);
    }
}

 

实现方式二:

特定于常量的方法实现(constant-specific method implementation)

public enum Operation {
    PLUS {
        double apply(double x, double y) {
            return x + y;
        }
    },
    MINUS {
        double apply(double x, double y) {
            return x - y;
        }
    },
    TIMES {
        double apply(double x, double y) {
            return x * y;
        }
    },
    DIVIDE {
        double apply(double x, double y) {
            return x / y;
        }
    };

    abstract double apply(double x, double y);
}

 

相关文章:

  • 2021-07-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-17
猜你喜欢
  • 2022-12-23
  • 2022-01-08
  • 2021-09-24
  • 2022-12-23
  • 2022-01-07
  • 2022-01-26
  • 2022-02-20
相关资源
相似解决方案