카테고리 없음

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

발망생 2023. 12. 16. 15:09

열거 타입은 거의 모든 상황에서 타입 안전 열거 패턴보다 우수하다.

 

- 타입 안전 열거 패턴

public class TypeSafeEnumPattern {

    private final String type;
    private TypeSafeEnumPattern(String type) {
        this.type = type;
    }

    public String toString() {
        return type;
    }

    public static final TypeSafeEnumPattern PLUS = new TypeSafeEnumPattern("+");
    public static final TypeSafeEnumPattern MINUS = new TypeSafeEnumPattern("-");
    public static final TypeSafeEnumPattern TIMES = new TypeSafeEnumPattern("*");
    public static final TypeSafeEnumPattern DIVIDE = new TypeSafeEnumPattern("/");
}

 

 

단, 예외가 하나 있으니, 타입 안전 열거 패턴은 확장할 수 있으나 열거 타입은 그럴 수 없다.

실수로 열거 타입을 확장할 수 없게 설계한 것이 아니다.

대부분 상황에서 열거 타입을 확장하는 건 좋지 않은 생각이다.

확장한 타입의 원소는 기반 타입의 원소로 취급하지만 그 반대는 성립하지 않는다면 매우 이상한 것이다.

public enum ExtendedEnumClass extends Basic{
}
=> 이런 상속 안됨

 

 

 

그런데 확장할 수 있는 열거 타입이 어울리는 쓰임이 최소한 하나는 있다. 바로 연산코드다.

연산 코드의 각 원소는 특정 기계가 수행하는 연산을 뜻한다.

 

다행히 인터페이스를 구현하는 방법으로 확장할 수 있는 방법이 있다.

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 "BasicOperation{" +
                "symbol='" + symbol + '\'' +
                '}';
    }
}

 

열거 타입인 BasicOperation은 확장할 수 없지만 인터페이스인 Operation은 확장할 수 있고, 이 인터페이스를 연산의 타입으로 사용하면 된다.

 

public enum ExtendedOperation implements Operation{
    EXP("^") {
        @Override
        public double apply(double x, double y) {
            return Math.pow(x, y);
        }
    },
    REMAINDER("%") {
        @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 "BasicOperation{" +
                "symbol='" + symbol + '\'' +
                '}';
    }

    public static void main(String[] args) {
        double x = 1.2;
        double y = 5.5;
        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));
        }
    }
}

 

새로 작성한 연산은 기존 연산을 쓰던 곳이면 어디든 쓸 수 있다. 개별 인스턴스 수준에서뿐 아니라 순회역시 가능하다

public static void main(String[] args) {
    double x = 1.2;
    double y = 5.5;
    test(ExtendedOperation.class, x, y);
    test(Arrays.asList(ExtendedOperation.values()), 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));
    }
}

private static 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));
    }
}

=>
1.200000 ExtendedOperation{symbol='^'} 5.500000 = 2.725818
1.200000 ExtendedOperation{symbol='%'} 5.500000 = 1.200000
1.200000 ExtendedOperation{symbol='^'} 5.500000 = 2.725818
1.200000 ExtendedOperation{symbol='%'} 5.500000 = 1.200000