需求: 根据工作时间来计算工人工资.
- 周一到周五,超过八个小时的部分会额外计算加班工资
- 周六周日的所有工作都会有额外工资
- 特别日双倍工资
?策略枚举类
public enum PayrollDay {
MONDAY(PayType.WEEKDAY, 1),
TUESDAY(PayType.WEEKDAY, 2),
WEDNESDAY(PayType.WEEKDAY, 3),
THURSDAY(PayType.WEEKDAY, 4),
FRIDAY(PayType.WEEKDAY, 5),
SATURDAY(PayType.WEEKEND, 6),
SUNDAY(PayType.WEEKEND, 7),
OTHER(PayType.SPECIAL, 99);
private final PayType payType;
private final Integer code;
PayrollDay(PayType payType, Integer code) {
this.payType = payType;
this.code = code;
}
public int pay(int minsWorked, int payRate) {
return payType.pay(minsWorked, payRate);
}
public static PayrollDay fromCode(int code) {
return Arrays.stream(PayrollDay.values()).filter(item -> item.code == code).findAny().orElse(null);
}
private enum PayType {
WEEKDAY {
@Override
int overtimePay(int minsWorked, int payRate) {
return minsWorked <= MINS_PER_SHIFT ? 0 : (minsWorked - MINS_PER_SHIFT) * payRate / 2;
}
},
WEEKEND {
@Override
int overtimePay(int minsWorked, int payRate) {
return minsWorked * payRate / 2;
}
},
SPECIAL {
@Override
int overtimePay(int minsWorked, int payRate) {
return minsWorked * payRate;
}
};
abstract int overtimePay(int minsWorked, int payRate);
private static final int MINS_PER_SHIFT = 8 * 60;
int pay(int minsWorked, int payRate) {
int basePay = minsWorked * payRate;
return basePay + overtimePay(minsWorked, payRate);
}
}
}
?调用
@Service
public class EnumTest implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
EnumSet enumset = EnumSet.range(PayrollDay.FRIDAY, PayrollDay.SUNDAY);
List<PayrollDay> payrollDays = new ArrayList<>();
enumset.forEach(item -> payrollDays.add((PayrollDay)item));
List<Staff> staff = List.of(
new Staff("1", 5, 500),
new Staff("1", 6, 500),
new Staff("1", 7, 600)
);
EnumMap<PayrollDay, Integer> payrollDayIntegerEnumMap = new EnumMap<>(PayrollDay.class);
staff.forEach(item -> payrollDayIntegerEnumMap.put(
PayrollDay.fromCode(item.getDay())
, item.getHour()
));
for (PayrollDay payrollDay : payrollDays) {
System.out.println(payrollDay.pay(payrollDayIntegerEnumMap.get(payrollDay), 2));
}
Integer salaryCount = payrollDays.stream()
.map(item -> item.pay(payrollDayIntegerEnumMap.get(item), 2))
.reduce(Integer::sum)
.orElse(0);
System.out.println("指定日期的工资共计为: " + salaryCount);
}
}
?效果
|