枚举列表与布尔类的列表

kun*_*gcc 4 java

现在,我有一个有字段的课.

@Entity
public class Fuel {

    @Id @GeneratedValue
    private Long id;

    private boolean diesel;
    private boolean gasoline;
    private boolean etanhol;
    private boolean cng;
    private boolean electric;

    public Fuel() {
        // this form used by Hibernate
    }

    public List<String> getDeclaredFields() {
        List<String> fieldList = new ArrayList<String>();

        for(Field field : Fuel.class.getDeclaredFields()){
            if(!field.getName().contains("_") && !field.getName().equals("id") && !field.getName().equals("serialVersionUID") ) {
                fieldList.add(field.getName());

            }
            Collections.sort(fieldList);
        }
        return fieldList;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public boolean isDiesel() {
        return diesel;
    }

    public void setDiesel(boolean diesel) {
        this.diesel = diesel;
    }

    public boolean isGasoline() {
        return gasoline;
    }

    public void setGasoline(boolean gasoline) {
        this.gasoline = gasoline;
    }

    public boolean isEtanhol() {
        return etanhol;
    }

    public void setEtanhol(boolean etanhol) {
        this.etanhol = etanhol;
    }

    public boolean isCng() {
        return cng;
    }

    public void setCng(boolean cng) {
        this.cng = cng;
    }

    public boolean isElectric() {
        return electric;
    }

    public void setElectric(boolean electric) {
        this.electric = electric;
    }   

}
Run Code Online (Sandbox Code Playgroud)

我认为这是有道理的,但当我问另一个问题时(可能是一个愚蠢的例子,因为只能有自动或手动变速箱)/sf/ask/822335111/ in-pojo,用户建议我使用枚举.像这样:

public enum Fuel {
    DIESEL("diesel"),
    GASOLINE("gasoline"),
    ETANHOL("etanhol"),
    CNG("cng"),
    ELECTRIC("electric");

    private String label;

    private Fuel(String label) {
        this.label = label;
    }

    public String getLabel() {
        return label;
    }

}
Run Code Online (Sandbox Code Playgroud)

但是,由于市场上存在混合动力车(如丰田普锐斯),因此父类将以这种方式实现布尔类:

private Fuel fuel = new Fuel();
Run Code Online (Sandbox Code Playgroud)

如果以这种方式使用枚举列表:

private List<Fuel> fuelList = new ArrayList<Fuel>();
Run Code Online (Sandbox Code Playgroud)

什么是最佳做法?请记住,我可能有100种不同的燃料(例如=).不要忘记它是一个实体,因此持久存储在数据库中.

在此先感谢=)

dje*_*lin 5

听起来像你想要一个EnumSet,是的,绝对超过了一堆bool.

这让我想起了很多标志的设计模式,我最近发布了一个SO问题: 正确的设计模式,用于将标志传递给对象

这支持容易地拥有100种不同的燃料类型.然而,它不支持同时使用100种不同燃料类型的汽车.但对我来说这听起来非常好 - 构建这样的汽车非常困难,这完全反映在编码这个程序的复杂性:)(除非当然它真的只是支持所有基于玉米的燃料 - 你在其中可能更喜欢多态模式.)