为什么不在OOP设计中使用instanceof运算符? [英] Why not use instanceof operator in OOP design?

查看:162
本文介绍了为什么不在OOP设计中使用instanceof运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经反复说,除了在equals()方法之外,不应该使用instanceof运算符,否则这是一个糟糕的OOP设计。



有些人写道,是一个沉重的操作,但似乎至少java,处理它很好(甚至比Object.toString()比较更有效)。



有人可以解释或者直接指引一些文章,解释为什么这是一个糟糕的设计?



考虑这一点:



<$ p $ ($动物动物:动物){
(动物动物:动物){
if(animal instanceOf Fish){
吃(动物);
}
else if(动物实例狗){
playWithIt(animal);
}
}
}
...
}

决定如何处理动物,取决于人。人的欲望也可以偶尔改变,决定吃狗,玩鱼,而动物不要改变。



如果你认为instanceof运算符不是在这里,正确的OOP设计,请告诉你如果没有instanceof你会怎么做,为什么?



谢谢。

解决方案

instanceof 只需打破开放/关闭原则和/或 Liskov替代原则



如果由于 instanceof 使用情况我们不够抽象,每次新的子类进入,可能会更新收集应用程序逻辑的主要代码。
这显然不是我们想要的,因为它可能会破坏现有的代码并降低其可重用性。



因此,应该优先使用多态超过基本使用条件。


It has been repeatedly said that the instanceof operator should not be used except in the equals() method, otherwise it's a bad OOP design.

Some wrote that this is a heavy operation, but it seems that, at least java, handles it pretty well (even more efficiently than Object.toString() comparison).

Can someone please explain, or direct me to some article which explains why is it a bad design?

Consider this:

Class Man{
  doThingsWithAnimals(List<Animal> animals){
    for(Animal animal : animals){
      if(animal instanceOf Fish){
        eatIt(animal);
      }
      else if(animal instanceof Dog){
        playWithIt(animal);
      }
    }
  }
  ...
}

The decision of what to do with the Animal, is up to the Man. Man's desires can also change occasionally, deciding to eat the Dog, and play with the Fish, while the Animals don't change.

If you think the instanceof operator is not the correct OOP design here, please tell how would you do it without the instanceof, and why?

Thanks.

解决方案

instanceof simply breaks the Open/Close principle. and/or Liskov substitution principle

If we are not enough abstract because of instanceof usage, each time a new subclass makes an entrance, the main code gathering the logic of the application might be updated. This is clearly not what we want, since it could potentially break the existing code and reduce its reusability.

Therefore, a good usage of polymorphism should be preferred over the basic use of conditional.

这篇关于为什么不在OOP设计中使用instanceof运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆