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

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

问题描述

已经反复说过,除了在equals()方法中不应该使用instanceof操作符,否则这是一个糟糕的OOP设计.

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.

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

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?

考虑一下:

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.

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

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?

推荐答案

instanceof 只是打破了 开/关原则. 和/或 里氏替换原则

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

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

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天全站免登陆