考虑创建具有足够大量枚举器和抽象方法的枚举有多糟糕

St.*_*rio 4 java enums

我有以下枚举:

public enum RuleItem {
    MORE_THAN(1) {
        @Override
        public String getStringRepresentation() {
            return getRuleStringRepresentation("rulesName.moreThan");
        }
    },
    LESS_THAN(2) {
        @Override
        public String getStringRepresentation() {
            return getRuleStringRepresentation("rulesName.lessThan");
        }
    },
    MORE_OR_EQUAL(3) {
        @Override
        public String getStringRepresentation() {
            return getRuleStringRepresentation("rulesName.moreOrEqual");
        }
    },

    //...

    INTERVAL_WITH_BOUNDS_INCLUDED(27) {
        @Override
        public String getStringRepresentation() {
            return getRuleStringRepresentation("rulesName.intervalWithBounds");
        }
    };
    protected String getRuleStringRepresentation(String resourceName) {
        Locale locale = FacesContext.getCurrentInstance().getViewRoot()
            .getLocale();
        String resourceString;
        try {
            ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_NAME,
                locale);
            resourceString = bundle.getString(resourceName);
        } catch (MissingResourceException e) {
            return null;
        }

        return resourceString;
    }

    public abstract String getStringRepresentation();
}
Run Code Online (Sandbox Code Playgroud)

我想添加三个更抽象的方法.enum是否包含大量的公共方法?也许我应该在这种情况下创建一个类?

Ori*_*ntz 14

为什么不简单地使用构造函数,例如:

public enum RuleItem {
    MORE_THAN(1, "rulesName.moreThan"),
    LESS_THAN(2, "rulesName.lessThan"),
    MORE_OR_EQUAL(3, "rulesName.moreOrEqual");

    private int value;
    private String representation;

    private RuleItem(int value, String representation) {
        this.value = value;
        this.representation = representation;
    }

    public String getStringRepresentation() {
         return representation;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以根据需要添加任意数量的参数和方法,但不必为每个值单独覆盖它(只需在构造函数中传递它).

  • construtor中的`representation`应该是`String`而不是`int`. (3认同)