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);
}
}
网友评论