我有以下枚举:
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();
}
我想添加三个更抽象的方法。 enum是否包含大量的公共方法?也许我应该在这种情况下创建一个类?
答案 0 :(得分: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;
}
}
然后,您可以添加尽可能多的参数和方法,但不要为每个值单独覆盖它(只需在构造函数中传递它)。
答案 1 :(得分:3)
我没有看到任何使用多种公共方法进行枚举的问题。枚举项本身就是对象。
我喜欢 Java enum
实现,原因就在于:你有对象而不是像C或C#中的裸值。
无论如何,枚举项应该是不可变对象,它们可以委托进一步详细说明其他对象。
public interface RuleExecutor {
public void execute(int param1, int param2);
}
public enum RuleItem {
MORE_THAN("rulesName.moreThan", new MoreThanExecutor()),
LESS_THAN("rulesName.lessThan" , new LessThanExecutor()),
MORE_OR_EQUAL("rulesName.moreOrEqual", new MoreOrEqualExecutor());
private String representation;
private RuleExecutor executor;
private RuleItem(String representation, RuleExecutor executor) {
this.representation = representation;
this.executor = executor;
}
public String getStringRepresentation() {
return getRuleStringRepresentation(representation);
}
public void execute(int param1, int param2) {
this.executor.execute(param1, param2);
}
}