本文介绍了切换实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个问题是使用 instanceof
对象的开关案例:
I have a question of using switch case for instanceof
object:
例如:我的问题可能是以Java再现:
For example: my problem can be reproduced in Java:
if(this instanceof A)
doA();
else if(this instanceof B)
doB();
else if(this instanceof C)
doC():
它是用开关实现的......案例
?
推荐答案
这是子类型多态性有助于的典型场景。执行以下操作
This is a typical scenario where subtype polymorphism helps. Do the following
interface I {
void do();
}
class A implements I { void do() { doA() } ... }
class B implements I { void do() { doB() } ... }
class C implements I { void do() { doC() } ... }
然后你只需在这个
上调用 do()
。
Then you can simply call do()
on this
.
如果您无法自由更改 A
, B
和 C
,您可以应用访客模式来实现相同目标。
If you are not free to change A
, B
, and C
, you could apply the visitor pattern to achieve the same.
这篇关于切换实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!