枚举转映射

枚举转映射对象

算奇技淫巧吧。不能算作设计模式,但是如此巧妙的设计,使得在给前端提供查询接口的时候,非常优雅
见代码
1.用此给前端展示数据dto

/**
 * 选项展示内容Dto
 *
 * @author 
 * @date 2024-11-28
 */
@SuperBuilder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class OptionItemDto implements Serializable {
    /**
     * 序列化ID
     */
    private static final long serialVersionUID = 1L;


    /**
     * 选项显示名称
     */
    private String label;
    /**
     * 选项值
     */
    private String value;
    /**
     * 选项描述
     */
    private String desc;

    /**
     * 选项是否默认选中
     */
    private Boolean selected;


}

2.枚举类ResType实现该接口

  • 核心是有一个final修饰的属性,属性的类型是OptionItemDto
  • 在构造函数的时候,隐式通过构造函数生成了该属性值
@Getter
public enum ResType implements Describable {
    /**
     * MySQL数据库
     */
    MYSQL("MySQL数据库", "MySQL数据库", "MySQL数据库巡检", true),
    ;

    /**
     * 资源类型名称
     */
    final String name;


    /**
     * 名称
     */
    private final String label;
    /**
     * 描述
     */
    private final String desc;

    /**
     * 是否默认
     */
    private final Boolean isDefault;

    /**
     * 获取枚举值
     *
     * @return 值
     */
    @Override
    public String getValue() {
        return this.name();
    }

    /**
     * 获取枚举值默认显示方式Dto
     */
    private final OptionItemDto optionItemDto;


    /**
     * 构造函数
     *
     * @param name 资源类型名称
     */
    ResType(String name, String label, String desc, Boolean isDefault) {
        this.name = name;
        this.label = label;
        this.desc = desc;
        this.isDefault = isDefault;
        this.optionItemDto = new OptionItemDto(this.label, this.name(), this.desc, isDefault);
    }
}

  1. 给前端提供数据时候
@GetMapping("/resType")
public List<OptionItemDto> getResTypes() {
    List<OptionItemDto> result = new ArrayList<>(ResType.values().length);
    for (ResType value : ResType.values()) {
        result.add(value.getOptionItemDto());
    }
    return result;
}
posted @ 2025-03-04 16:01  SpecialSpeculator  阅读(7)  评论(0)    收藏  举报