자료형
이다. 열거하는 방식을 통해 멤버들의 집합을 보여준다.정수 열거 패턴
을 사용하여 코드를 관리하였다정수 열거 패턴
은 다음 3가지 문제를 갖는다.public static final int ORDER_ACCEPT = 10; // 주문접수
public static final int ORDER_COMPLETE = 20; // 주문완료
public static final int ORDER_CANCEL = 30; // 주문취소
public static final int DELIVERY_ACCEPT = 10; // 배달접수
public static final int DELIVERY_COMPLETE = 20; // 배달완료
public static final int DELIVERY_CANCEL = 30; // 배달취소
public enum Order {Accept, Complete, Cancel}
public enum Delivery {Accept, Complete, Cancel}
클래스
다생성자
를 제공하지 않기 때문에 final
이다==
연산은 true가 된다.public enum Order {Accept, Complete, Cancel}
public static void main(String[] args) {
Order order1 = null;
Order order2 = null;
order1 = Order.Accept;
order2 = Order.Accept;
System.out.println("order1 == Order.Accept : " + (order1 == Order.Accept));
System.out.println("order1 == order2 : " + (order1 == order2));
}
(결과)는 역시 모두 true다
order1 == Order.Accept : true
order1 == order2 : true
public class GoodEnum {
enum PayrollDay{
MONDAY(PayType.WEEKDAY), TUESDAY(PayType.WEEKDAY), WEDNESDAY(PayType.WEEKDAY),
THURSDAY(PayType.WEEKDAY), FRIDAY(PayType.WEEKDAY), SATURDAY(PayType.WEEKEND),
SUNDAY(PayType.WEEKEND);
private final PayType payType;
PayrollDay(PayType payType){
this.payType = payType;
}
int pay(int minutesWorked, int payRate){
return payType.pay(minutesWorked, payRate);
}
// 전략 열거 타입
enum PayType{
WEEKDAY{
int overtimePay(int minsWorked, int payRate){
return minsWorked <= MINS_PER_SHIFT ? 0
: (minsWorked - MINS_PER_SHIFT) * payRate / 2;
}
},
WEEKEND{
int overtimePay(int minsWorked, int payRate){
return minsWorked * payRate / 2;
}
};
private static final int MINS_PER_SHIFT = 8 * 60;
abstract int overtimePay(int mins, int payRate);
int pay(int minsWorked, int payRate){
int basePay = minsWorked * payRate;
return basePay * overtimePay(minsWorked, payRate);
}
}
}
}
public static void main(String[] args) {
// Example 1: Calculate pay for a weekday
int weekdayPay = PayrollDay.MONDAY.pay(9 * 60, 10); // Worked 9 hours, $10 per hour
System.out.println("Weekday Pay: $" + weekdayPay);
// Example 2: Calculate pay for a weekend
int weekendPay = PayrollDay.SATURDAY.pay(6 * 60, 12); // Worked 6 hours, $12 per hour
System.out.println("Weekend Pay: $" + weekendPay);
}
Weekday Pay: $1620000
Weekend Pay: $9331200