Enum(열거형) Class

어겐어갠·2022년 4월 13일
0
public enum VoucherType {
    FIXED(1, amount -> new FixedAmountVoucher(UUID.randomUUID(), amount)),
    PERCENT(2, amount -> new PercentDiscountVoucher(UUID.randomUUID(), amount));

    private final int number;
    private Function<Long, Voucher> createVoucherExpression;

    VoucherType(int number, Function<Long, Voucher> createVoucherExpression) {
        this.number = number;
        this.createVoucherExpression = createVoucherExpression;
    }

    public int getNumber() {
        return number;
    }

    public Voucher createVoucher(long amount) {
        return createVoucherExpression.apply(amount);
    }

    public static VoucherType getVoucherType(int inputVoucherTypeInt) {
        VoucherType voucherType = Arrays.stream(VoucherType.values())
                .filter(v -> v.getNumber() == inputVoucherTypeInt)
                .findFirst()
                .orElseThrow(IllegalArgumentException::new);
        return voucherType;
    }

Enum에 대한 활용도가 떨어진다는 지적을 받아서 공부하게되었다.

기존에는 단순히 Enum은 필드값으로만 썻고 이번에 공부하면서 Enum의 가치를 느낄 수 있었다.

  1. 데이터 간의 연관관계가 표현된다.
FIXED(1, amount -> new FixedAmountVoucher(UUID.randomUUID(), amount))

을 보게되면 FIXED 와 1의 연관관계를 만들어주었다.

  1. 함수형 인터페이스를 사용하여 데이터와 메서드를 연결할 수 있었다.

  2. 또한 데이터에 Array를 넣어 데이터 그룹을 관리하는데에도 사용할 수 있다.

또한 Enum Class안에 데이터의 유무를 검증하는 메서드를 구현할 수 있었으며, Swich - case에 사용되어 if를 줄이는데 큰 도움을 받을 수 있었다.

https://techblog.woowahan.com/2527/

profile
음그래

0개의 댓글