基于类中字段的选择方法 [英] Select method based on field in class
问题描述
所以我有一个包含字符串字段的类:
So I have a class that contains a String-field:
public class A {
private String type = ...
public String getType(){
return this.type;
}
public void setType(String type){
this.type = type;
}
}
我还列出了所有可能的类型,将来有十二种,甚至可能更多.
I also have a list of all possible types, there are twelve and possibly more in the future.
现在,我想编写一个获取类A对象并根据类中的类型"调用特定方法的方法.
有没有比编写12个(或更多)if语句更智能的解决方案?
通常,我会使用访客"模式,但我不想创建十二个新类.
Now I want to write a method that gets an object of class A and calls a specific method depending on which "type" is in the class.
Is there a smarter solution than writing 12 (or more) if-statements?
Normally I would use the Visitor-pattern but I don't want to create twelve new classes.
我最终创建了一个
edit:
I ended up creating a
Map<String,Function<A,String>> map = new HashMap<String,Function<A,String>>
然后致电
A a;
...
map.get(a.getType).apply(a);
推荐答案
您应该使用enum
,而不是将类型存储为自由格式"文本值,因为您有定义明确的值列表
Instead of storing type as a "free-form" text value, you should be using an enum
, since you have a well-defined list of values.
通过使用抽象方法,您甚至可以让不同的枚举以不同的方式实现相同的方法.这将使您完全消除容易出错的switch
语句.
You can even have the different enums implement the same method differently, by using an abstract method. This will allow you to totally eliminate the error-prone switch
statements.
下面是同时显示实例值和抽象方法的示例.显示的模式将使实现不受枚举的影响,同时使编译器在添加新的枚举时捕获所有用途.
Below is an example showing both instance values and abstract methods. The pattern shown will keep the implementation out of the enum, while having the compiler catch all uses when a new enum is added.
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
语句,您将不会获得这种安全性.
When you add a new type to the TYPE enum, you also add a new method to the Action interface, which will force you to implement that method in all implementations of the interface. With switch
statements, you'd get no such safety.
这篇关于基于类中字段的选择方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!