您应该使用枚举,而不是将类型存储为“自由格式”文本值,因为您有一个明确定义的值列表.
通过使用抽象方法,您甚至可以使不同的枚举以不同方式实现相同的方法.这将允许您完全消除容易出错的switch语句.
下面是一个显示实例值和抽象方法的示例.显示的模式将使实现不在枚举中,同时让编译器在添加新枚举时捕获所有用途.
public enum Type {
INTEGER("Integer") {
@Override
public void apply(Action action, A a) {
action.applyInteger(a);
}
},
STRING ("Text") {
@Override
public void apply(Action action, A a) {
action.applyString(a);
}
};
private String displayName;
private Type(String displayName) {
this.displayName = displayName;
}
public String getDisplayName() {
return this.displayName;
}
public abstract void apply(Action action, A a);
}
public interface Action {
public void applyInteger(A a);
public void applyString(A a);
}
public class A {
private Type type;
public Type getType(){
return this.type;
}
public void setType(Type type){
this.type = type;
}
public void apply(Action action) {
this.type.apply(action, this);
}
}
向TYPE枚举添加新类型时,还会向Action接口添加新方法,这将强制您在接口的所有实现中实现该方法.使用switch语句,您将无法获得此类安全性.