如何使用多态而不是instanceof? (为什么?) [英] How does one use polymorphism instead of instanceof? (And why?)

查看:181
本文介绍了如何使用多态而不是instanceof? (为什么?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们采用以下代码:

If we take the code below:

Shape p1 = new Square();
Square c1;
if(p1 instanceof Square) {
  c1 = (Square) p1;
}

偏好多态到 instanceof ,顺便说一句,为什么它更好?

What does it mean to prefer polymorphism to instanceof, and incidentally, why is it better?

编辑:我明白什么是多态是;我缺少的是如何使用它而不是 instanceof

I understand what polymorphism is; what I'm missing is how one would use it rather than instanceof.

推荐答案

if ... else ...(或switch,或者访问者)和多态之间的主要区别是模块性。有一种所谓的开放闭合原则,它基本上意味着,当您向现有程序添加新功能时,您在现有代码中所做的更改越少越好(因为每次更改都需要一些工作,并且可能会引入错误)。所以让我们比较一下变化的数量:

The main difference between if...else... (or switch, or Visitor), and between polymorphism is modularity. There's so called open-closed principle, which basically means, that when you add a new feature to an existing program, the less changes you make in existing code the better (because every change requires some work, and may introduce bugs). So let's compare the amount of changes:


  • 添加一个新方法(例如你有paint()和getArea() ,让我们添加getCircumference()):使用if-else解决方案,您只需要改变一个文件 - 包含新方法的文件。使用多态,你必须改变你所有的Shape类实现。

  • adding a new method (eg. you have paint(), and getArea(), let's add getCircumference()): with if-else solution you only have to alter just one file - the file which will contain the new method. With polymorphism, you have to alter all your implementations of Shape class.

添加一种新的Shape(你有Square,Circle - 让我们添加Triangle):使用if-else解决方案,您必须使用if-else查看所有现有类,并为Triangle添加新的if分支;你可以使用多态性来添加一个新类并在其中实现所有必需的方法。

adding a new kind of Shape (you have Square, Circle - let's add Triangle): with if-else solution you have to review all existing classes with if-else and add a new if branch for Triangle; with polymporphism all you have is to add a new class and implement all required methods in it.

所以如果.. .else ...或多态:它取决于模块性。如果您希望以后添加许多新子类,请使用多态;如果您希望以后添加许多新方法,请使用if ... else ...,并在类中只放置最基本的方法,如访问器。或者换句话说:当你期望有很多if ... else ...分支时,你应该使用多态,当你期望很少这样的分支时,只要留下来,如果......其他......

So if...else... or polymorphism: it depends on modularity. If you expect that many new sublasses will be added later, use polymorphism; if you expect that many new methods will be added later, use if...else..., and in the class put only the most "basic" methods like accessors. Or in other words: when you expect to have many if...else... branches, you should rather use polymorphism, when you expect few such branches, just stay with if...else...

另外:当你期望很少的if ... else ...分支,但在很多地方,你应该考虑封装这个如果... else ...与访客模式或只是为每个分支制作一个带有单独案例的枚举。

Additionally: when you expect few if...else... branches, but in lots of places, you should consider encapsulating this if...else... with Visitor pattern or just making an enum with a separate case for each branch.

这篇关于如何使用多态而不是instanceof? (为什么?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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