NMP-Study / EffectiveJava2022

Effective Java Study 2022
5 stars 0 forks source link

아이템 38. 확장할 수 있는 열거 타입이 필요하면 인터페이스를 사용하라 #38

Closed okhee closed 2 years ago

bluewbear commented 2 years ago

확장할 수 있는 열거 타입이 필요하면 인터페이스를 사용하라

public interface Operation {
    double apply(double x, double y);
}
public enum BasicOperation implements Operation {
    PLUS("+") {
        @Override
        public double apply(double x, double y) {
            return x + y;
        }
    },
    MINUS("-") {
        @Override
        public double apply(double x, double y) {
            return x - y;
        }
    },
    TIMES("*") {
        @Override
        public double apply(double x, double y) {
            return x * y;
        }
    },
    DIVIDE("/") {
        @Override
        public double apply(double x, double y) {
            return x / y;
        }
    };

    private final String symbol;

    BasicOperation(String symbol) {
        this.symbol = symbol;
    }

    @Override
    public String toString() {
        return symbol;
    }
}
public enum ExtendedOperation implements Operation {
    EXP("^") {
        @Override
        public double apply(double x, double y) {
            return Math.pow(x, y);
        }
    },
    REMATINDER("%") {
        @Override
        public double apply(double x, double y) {
            return x % y;
        }
    };

    private final String symbol;

    ExtendedOperation(String symbol) {
        this.symbol = symbol;
    }

    @Override
    public String toString() {
        return symbol;
    }
}
public class Page215Ex {
    public static void main(String[] args) {
        double x = Double.parseDouble("12");
        double y = Double.parseDouble("34");

        test(ExtendedOperation.class, x, y);
    }

    private static <T extends Enum<T> & Operation> void test(Class<T> opEnumType, double x, double y) {
        for (Operation op : opEnumType.getEnumConstants()) {
            System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y));
        }
    }
}
12.000000 ^ 34.000000 = 4922235242952026400000000000000000000.000000
12.000000 % 34.000000 = 12.000000

Process finished with exit code 0
public class SecondEx {
    public static void main(String[] args) {
        double x = Double.parseDouble("12");
        double y = Double.parseDouble("34");

        test(Arrays.asList(ExtendedOperation.values()), x, y);
    }

    private static <T extends Enum<T> & Operation> void test(Collection<? extends Operation> opSet, double x, double y) {
        for (Operation op : opSet) {
            System.out.printf("%f %s %f = %f%n", x, op, y, op.apply(x, y));
        }
    }
}
12.000000 ^ 34.000000 = 4922235242952026400000000000000000000.000000
12.000000 % 34.000000 = 12.000000

Process finished with exit code 0

핵심 정리