使用 instanceOf 检查消除条件语句
Eliminating a conditional statement with instanceOf checks
我有以下方法:
@Override
public <T> T method(T object){
if(object instanceOf Type1){
...
}
elseif(object instanceOf Type2){
...
}
...
}
object
始终是 SuperType
类型,而 Type1
、Type2
、... 都是 SuperType
的子类型。我无权访问任何类型 SuperType
、Type1
等,因此我无法更改它们。
我想删除这个有很多 if
-s 和 instanceOf
检查的结构。为此,我尝试实现访问者模式,但没有成功,因为我无法修改上述任何类型。
有人知道这个例子的好的解决方案吗?谢谢!
你可以派遣table。
private final static Map<Class<?>, Handler> dispatch = ....
// contains things like Type2.class -> Type2Handler
dispatch.get(object.getClass()).handle(object);
// may need to iterate superclasses if that is a concern
但不确定这样是否更好。
我有以下方法:
@Override
public <T> T method(T object){
if(object instanceOf Type1){
...
}
elseif(object instanceOf Type2){
...
}
...
}
object
始终是 SuperType
类型,而 Type1
、Type2
、... 都是 SuperType
的子类型。我无权访问任何类型 SuperType
、Type1
等,因此我无法更改它们。
我想删除这个有很多 if
-s 和 instanceOf
检查的结构。为此,我尝试实现访问者模式,但没有成功,因为我无法修改上述任何类型。
有人知道这个例子的好的解决方案吗?谢谢!
你可以派遣table。
private final static Map<Class<?>, Handler> dispatch = ....
// contains things like Type2.class -> Type2Handler
dispatch.get(object.getClass()).handle(object);
// may need to iterate superclasses if that is a concern
但不确定这样是否更好。