根据传入参数不同调用不同的方法:枚举方式

2019-07-16  本文已影响0人  莫夏_b560

public enum Operator {

    ADD {
        @Override
        public int apply(int a, int b) {
            return a + b;
        }
    },

    MULTIPLY {
        @Override
        public int apply(int a, int b) {
            return a * b;
        }
    },

    SUBTRACT {
        @Override
        public int apply(int a, int b) {
            return a - b;
        }
    },

    DIVIDE {
        @Override
        public int apply(int a, int b) {
            return a / b;
        }
    },

    MODULO {
        @Override
        public int apply(int a, int b) {
            return a % b;
        }
    };


    public abstract int apply(int a, int b);

    }
public class Calculator {
    public int calculate(int a, int b, Operator operator) {
        return operator.apply(a, b);
    }
}
public class Test {


    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        int num = calculator.calculate(3,4, Operator.valueOf("ADD")); //Operator.valueOf("ADD") == Operator.ADD
        System.out.println(num);
    }
}
上一篇下一篇

猜你喜欢

热点阅读