且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不在 OOP 设计中使用 instanceof 运算符?

更新时间:2023-11-14 09:29:52

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.