我正在学习 Cay Horstmann 的 Java For Everyone。
当它说的时候我有点困惑:
Don't Use Type Tests
这是关于使用 instanceof
运算符进行特定类型测试,以实现随每个类而变化的行为,例如(直接取自本书):
if (q instanceof ChoiceQuestions) //Don't do this
{
//Do the task the ChoiceQuestion way
}
else if (q instanceof Question)
{
//Do the task Question way
}
显然,这是一种糟糕的方法,因为如果您添加了一个新类,如 NumericQuestion
,您需要修改程序中进行类型测试的所有部分,添加另一个案例。
最好在程序中添加类NumericQuestion
。没有什么需要改变的,因为我们使用的是多态性,而不是类型测试。
当您发现自己尝试在类的层次结构中使用类型测试时,请重新考虑并改用多态性。在父类(super class)中声明一个方法doTheTask
,在子类中覆盖它并调用q.doTheTask()
我不明白的是最后一段,就是上面那一段。有人可以给我举个例子吗? (我是一种视觉学习者)。我们如何在不使用类型测试的情况下实际做到这一点?
最佳答案
重点是,而不是这个:
if (q instanceof ChoiceQuestions) //Don't do this
{
//Do the task the ChoiceQuestion way
}
else if (q instanceof Question)
{
//Do the task Question way
}
你应该这样做:
q.doTheTask();
Question
类包含:
public void doTheTask(String someParameter){
//Do the task Question way
}
ChoiceQuestion
类包含
public void doTheTask(String someParameter){
//Do the task the ChoiceQuestion way
}
然后,当你得到一个新类DrawQuestion
时,它会包含
public void doTheTask(String someParameter){
//Do the task the DrawQuestionway
}
但是 调用 doTheTask()
的代码都不必更改!没有风险,因为 if (q instanceof ChoiceQuestions )
模式,忘记添加新逻辑。并且(从长远来看,这实际上是更重要的部分)与特定类型的 Question
有关的所有逻辑都集中在一个类中,而不是分布在应用程序的所有部分。
关于java - 不要使用类型测试,声明 doTheTask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8693089/