How to avoid large if-statements and instanceof(如何避免大型 if 语句和 instanceof)
问题描述
动物
狮子
鹿
TestAnimals
有没有更好的方法来遍历列表而不必强制转换?在上述情况下,它似乎没问题,但如果你有许多基类的扩展,那么我们也需要那么多 if 块.有设计吗解决这个问题的模式或原则?
Is there a better way to iterate through the list without having to cast ?In the above case it seem's ok but if you have many extensions of the base class then we'll need that many if block too.Is there a design pattern or principle to address this problem ?
推荐答案
一种避免 instanceof
的优雅方法,无需在基类中发明一些新的人工方法(使用非描述性名称,例如 performAction
或 doWhatYouAreSupposedToDo
) 是为了使用 访问者模式.这是一个例子:
An elegant way of avoiding instanceof
without inventing some new artificial method in the base class (with a non-descriptive name such as performAction
or doWhatYouAreSupposedToDo
) is to use the visitor pattern. Here is an example:
动物
狮子和鹿
访客
TestAnimals
这篇关于如何避免大型 if 语句和 instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!