【问题标题】:Eliminating a conditional statement with instanceOf checks使用 instanceOf 检查消除条件语句
【发布时间】:2016-01-13 09:31:08
【问题描述】:

我有以下方法:

@Override
public <T> T method(T object){
    if(object instanceOf Type1){
    ...
    }
    elseif(object instanceOf Type2){
    ...
    }
    ...
}

object 始终是 SuperType 类型,Type1, Type2, ... 都是 SuperType 的子类型。我无权访问SuperTypeType1 等任何类型,因此无法更改它们。

我想消除这个有很多 if-s 和 instanceOf 检查的结构。为此,我尝试实现访问者模式,但它不起作用,因为我无法修改上述任何类型。

有人知道这个例子的好解决方案吗?谢谢!

【问题讨论】:

  • 不会避免instanceof,但如果object 始终是SuperType 类型,您可能应该声明&lt;T extends SuperType&gt;
  • 该方法是我无权访问的类型的重写版本,方法签名应该保持不变。

标签: refactoring instanceof visitor-pattern


【解决方案1】:

你可以有一个调度表。

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

但不确定是否更好。

【讨论】:

  • 它似乎至少更容易维护:)
猜你喜欢
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多