英文:
Need to make different objects in the same array react differently
问题
我正在创建一个用于处理包含来自相同父类的三个子类对象的数组的方法。当第三个类执行特定动作时,我希望其中两个类有不同的反应。我是否应该在数组上使用循环,然后结合使用 .getClass() 和 if-else-if 语句,根据 .getClass() 来决定如何处理每个对象呢?
英文:
I am making a method to use on a array that has objects from 3 child classes of the same parent class. I want two of the classes to react differently, when third class does a certain action. Would I use a loop on the array with a .getClass() and a if-else-if statement as to what to do with each of the objects based off of the .getClass()?
答案1
得分: 1
虽然从理论上讲这可能会起作用,但基于类类型的 if-else-if
开关通常被视为代码异味。
虽然你没有提供太多关于你想要的行为和反应的额外信息,但作为第一步,请考虑以下内容:你想要从这些类中获得的“反应”可以合理地被视为类的一个方法吗?它是否可以成为父类的方法,供子类根据需要进行重写?
(可以想象一个经典的例子,一个类 Animal
有一个方法 makeSound()
,然后有一个类 Dog
对其进行重写以输出 Bark!
,还有一个类 Cat
重写它以输出 Meow!
)
你可以在这里查找一些想法:https://refactoring.guru/smells/switch-statements
或者提供额外的信息,以便我们可以找出一个很好的重构方法,避免使用 switch 块。
英文:
While that would theoretically work, using if-else-if
switches based on class's type is often considered a code smell.
There isn't a lot of extra info you give as to what sort of behavior and reaction you're looking for but as first step consider this: Can the "reaction" you want to get from the classes reasonably be considered to be a method of the class, and could it be a method of the parent class that the child classes override as needed?
(Think of the classical example with a class Animal
and a method makeSound()
and then a class Dog
that overrides it to output Bark!
and a class Cat
that overrides it to output Meow!
)
You might check here for a few ideas: https://refactoring.guru/smells/switch-statements
or provide extra info so we can figure out a good refactoring to avoid the switch block.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论