use*_*213 3 java field visitor-pattern
所以我有一个包含字符串字段的类:
public class A {
private String type = ...
public String getType(){
return this.type;
}
public void setType(String type){
this.type = type;
}
}
Run Code Online (Sandbox Code Playgroud)
我还列出了所有可能的类型,将来有十二种甚至更多.
现在我想编写一个获取类A对象的方法,并根据类中的"类型"调用特定方法.有没有比编写12个(或更多)if语句更聪明的解决方案?
通常我会使用访问者模式,但我不想创建十二个新类.
编辑:
我最终创建了一个
Map<String,Function<A,String>> map = new HashMap<String,Function<A,String>>
Run Code Online (Sandbox Code Playgroud)
然后打电话
A a;
...
map.get(a.getType).apply(a);
Run Code Online (Sandbox Code Playgroud)
您应该使用a enum,而不是将类型存储为"自由格式"文本值,因为您有一个明确定义的值列表.
通过使用抽象方法,您甚至可以使不同的枚举以不同方式实现相同的方法.这将允许您完全消除容易出错的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);
}
}
Run Code Online (Sandbox Code Playgroud)
向TYPE枚举添加新类型时,还会向Action接口添加新方法,这将强制您在接口的所有实现中实现该方法.有了switch陈述,你就没有这种安全感了.