通过枚举值调用函数

在做业务的时候,需要根据前端传递的不同枚举参数(比如说0,1)返回对应固定的值。但是这个值需要根据时间又有所变化。我们可以使用if-else去实现对应的逻辑,比如说,当前端传递参数为0是,需要返回当月一号到当前日期的号数。当传递的参数为1时,需要返回当前年份的1月到当前日期的月份。我们可以进行如下处理

public List<Integer> test(Integer type){
    if(type == 0){
        // 对应生成天数的代码
    }else if(type == 1){
        // 对应生成月份的代码
    }
    return ...;
}

 这是枚举值较少的时候,我们这么做也不是不能接受,但是当参数较多时,我们最好还是使用枚举来减少if-else的出现。因此,使用枚举类来处理时,上述代码可以化简为

@Getter
@AllArgsConstructor
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum DateTypeEnum {
    /**
     * 生成 00:00 至 当前时间最近15分钟的时间段集合
     */
    DAY(1, () -> {
        LocalTime current = LocalTime.now().truncatedTo(ChronoUnit.MINUTES);
        LocalTime startTime = LocalTime.MIDNIGHT;
        List<String> intervals = new ArrayList<>();
        while (!startTime.isAfter(current)) {
            intervals.add(startTime.toString());
            startTime = startTime.plusMinutes(15);
        }
        return intervals;
    }),
    /**
     * 生成当前月份1号至当前日期的时间段集合
     */
    MONTH(2, () -> {
        int dayOfMonth = LocalDate.now().getDayOfMonth();
        List<String> days = new ArrayList<>();
        for (int i = 1; i <= dayOfMonth; i++) {
            days.add(String.valueOf(i));
        }
        return days;
    }),
    /**
     * 生成当年1月份至当前月份的时间段集合
     */
    YEAR(3, () -> {
        LocalDate current = LocalDate.now();
        int currentMonth = current.getMonthValue();
        List<String> dateList = new ArrayList<>();
        for (int i = 1; i <= currentMonth; i++) {
            dateList.add(Month.of(i).getDisplayName(TextStyle.FULL, Locale.CHINA));
        }
        return dateList;
    });
    private Integer code;
    private Supplier<List> desc;
    public static final List<DateTypeEnum> LIST =
            Arrays.stream(values()).toList();
    public static final Map<Integer, DateTypeEnum> MAP = LIST.stream()
            .collect(Collectors.toMap(DateTypeEnum::getCode, f -> f));

    public static DateTypeEnum ofCode(Integer code) {
        return MAP.get(code);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zmbwcx2003

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值