有人可以推荐Java 8模式来代替switch语句吗? [英] Can somebody recommend a java 8 pattern to replace a switch statement?
问题描述
我有以下代码:
public class A {
private String type;
String getType() { return type;}
}
现在在很多代码位置,我都有这样的代码
Now in many code places I have code like this
switch (a.geType()) {
case "A" : return new Bla();
case "B" : return new Cop();
}
或其他地方
switch (a.geType()) {
case "A" : return new Coda();
case "B" : return new Man();
}
(请注意,我知道我应该在生产代码中使用枚举).
(Note that I know I should use an Enumeration in production code).
我要实现的是,当将新类型添加到类A时,编译器应标记所有需要调整的switch语句?
What I want to achive is that when a new type is added to class A the compiler should flag all the switch statements that need to be adjusted?
是否有Java惯用的方式来做到这一点?
Is there a java idiomatic way to do this?
推荐答案
将新类型添加到
class A
时,编译器应标记所有需要调整的switch
语句吗?
when a new type is added to
class A
the compiler should flag all theswitch
statements that need to be adjusted?
一种好的方法是将switch
语句替换为 multiple dispatch 的更可靠实现,例如
A good approach to this would be replacing switch
statements with a more robust implementation of multiple dispatch, such as the Visitor Pattern:
interface VisitorOfA {
Object visitA(A a);
Object visitB(B b);
}
class A {
Object accept(VisitorOfA visitor) {
return visitor.visitA(this);
}
}
class B extends A {
Object accept(VisitorOfA visitor) {
return visitor.visitB(this);
}
}
有了此基础架构,您可以删除您的switch
语句,将其替换为访客的实现:
With this infrastructure in place, you can remove your switch
statements, replacing them with implementations of the visitor:
Object res = a.accept(new VisitorOfA() {
public Object visitA(A a) { return new Bla(); }
public Object visitB(B b) { return new Cop(); }
});
在A
中添加新的子类型(例如class C
)时,您要做的就是在VisitorOfA
中添加新方法:
When you add a new subtype to A
, say, class C
, all you need to do is adding a new method to VisitorOfA
:
Object visitC(C c);
现在,编译器将发现所有尚未实现此新方法的地方,从而帮助您避免在运行时出现问题.
Now the compiler will spot all places where this new method has not been implemented, helping you avoid problems at runtime.
这篇关于有人可以推荐Java 8模式来代替switch语句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!