
Contents
Enum 의 올바른 활용법Enum 의 올바른 활용법
생각보다 Enum을 활용하면 되는걸
그냥 자꾸 상수 집합체로만 사용하는 경향이 있어서
이번 기회에 예시들로 알아보려한다
기본적 형태
public enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}값이 있는 경우
public enum Size {
SMALL("S", 85),
MEDIUM("M", 90),
LARGE("L", 95),
XLARGE("XL", 100);
// final 필드
private final String code;
private final int chestSize;
// 생성자
Size(String code, int chestSize) {
this.code = code;
this.chestSize = chestSize;
}
public String getCode() {
return code;
}
public int getChestSize() {
return chestSize;
}
}비즈니스 로직들
Enum 에서 정적 메서드는 값을 찾는 용도로 활용
Enum에서 인스턴스 메서드는 동작또는 상태를 활용할 때
public enum Season {
SPRING("봄", 3, 5) {
@Override
public String getActivity() {
return "꽃구경";
}
},
SUMMER("여름", 6, 8) {
@Override
public String getActivity() {
return "수영";
}
},
FALL("가을", 9, 11) {
@Override
public String getActivity() {
return "단풍구경";
}
},
WINTER("겨울", 12, 2) {
@Override
public String getActivity() {
return "스키";
}
};
private final String koreanName;
private final int startMonth;
private final int endMonth;
Season(String koreanName, int startMonth, int endMonth) {
this.koreanName = koreanName;
this.startMonth = startMonth;
this.endMonth = endMonth;
}
// 추상 메서드 (각 상수가 구현)
public abstract String getActivity();
// 공통 메서드
public boolean isMonth(int month) {
if (startMonth <= endMonth) {
return month >= startMonth && month <= endMonth;
} else {
// 겨울 (12, 1, 2)
return month >= startMonth || month <= endMonth;
}
}
// 정적 메서드
public static Season fromMonth(int month) {
for (Season season : values()) {
if (season.isMonth(month)) {
return season;
}
}
throw new IllegalArgumentException("Invalid month: " + month);
}
}
// 사용
Season current = Season.fromMonth(3);
System.out.println(current); // SPRING
System.out.println(current.getActivity()); // "꽃구경"
System.out.println(Season.WINTER.isMonth(1)); // true여기서 fromMonth 라는 정적 메서드를 통해 값을 반환하고 있다
조금만 생각해보면 되는 것
public enum PaymentMethod {
CARD("신용카드", "C"),
CASH("현금", "M"),
POINT("포인트", "P");
private final String name;
private final String code;
PaymentMethod(String name, String code) {
this.name = name;
this.code = code;
}
// static : 코드로 결제수단 찾기
public static PaymentMethod fromCode(String code) {
for (PaymentMethod method : values()) {
if (method.code.equals(code)) {
return method;
}
}
return null;
}
// 이유: 코드만 알고 있고, PaymentMethod를 모를 때 사용
// static : 이름으로 결제수단 찾기
public static PaymentMethod fromName(String name) {
for (PaymentMethod method : values()) {
if (method.name.equals(name)) {
return method;
}
}
return null;
}
// 이유: 이름만 알고 있고, PaymentMethod를 모를 때 사용
// 인스턴스 : "이 결제수단"의 코드
public String getCode() {
return code;
}
// 이유: 이미 PaymentMethod를 알고 있고, 그것의 코드가 필요할 때
// 인스턴스 : "이 결제수단"이 카드인가?
public boolean isCard() {
return this == CARD;
}
// 이유: 특정 PaymentMethod에 대한 판단
}
// 사용 시나리오
public class Payment {
public void processPayment(String paymentCode, int amount) {
// static : 코드로 결제수단 찾기
PaymentMethod method = PaymentMethod.fromCode(paymentCode);
if (method == null) {
throw new IllegalArgumentException("잘못된 결제 코드");
}
// 인스턴스 : 카드 결제인지 확인
if (method.isCard()) {
// 카드 결제 처리
System.out.println("카드 결제: " + amount + "원");
} else {
// 기타 결제 처리
System.out.println(method.getCode() + " 결제: " + amount + "원");
}
}
}정확한 사용 시점
고정된 값들의 집합체
예시처럼 요일, 수단, 연산자, 우선순위 등 변동이 적은 고정 집합체를 표현할 때
자주 변경되는 값들엔 사용하지 말기
상품의 카테고리 (동적 요소 다분)
사용자 태그
Share article