我有以下基类层次结构:
索引
(摘要)根索引
AbstractSubIndex
(摘要)
然后我还有两门课:
KPI
,应继承AbstractSubIndex
,并添加自身独有的功能;SubIndex
,它应该继承AbstractSubIndex
的功能以及RootIndex
中的功能。我会选择默认方法 (Java 8),但我的代码无法在接口(interface)
(实例变量)中编写。
更新
请注意,Index
具有在其他类中继承的默认构建后功能;此构建后功能必须执行一次。组合将迫使它至少执行两次,这使得组合对我来说是一个不可行的解决方案。
结束更新
我找不到任何非冗余的方法来解决这个问题。
有什么想法吗?
最佳答案
这个解决方法对我来说很奇怪,它是基于组合的 - 感谢 @kinga93 和 @AlexR 的建议以及从头开始的面向方面的设计 - 但在基类的原始代码中进行了更多调整,这是我尽力避免的。
请注意,我已经将 @webuster 的解决方案标记为可接受的解决方案,因为它更简单,并且可以完成工作。我发布这个是因为这是我最终选择的,因为从设计的角度来看它对我来说更有意义,而且以防万一有人需要它。
- 我从
RootIndex
中获取了不基于Index
的代码,并将其包装在类ParentBehaviour
中,并在它的位置。 - 我在
AbstractSubIndex
中做了同样的事情,获取不基于Index
的代码,并将其包装在另一个类ChildBehavior
中,并且在其位置添加引用。 - 我在
SubIndex
中使用了组合,并引用了ParentBehavior
和ChildBehavior
,同时继承了AbstractSubIndex
。 - 我在
KPI
中再次使用了组合,继承自AbstractSubIndex
,同时引用了ChildBehavior
。
最终的代码是这样的:
class ParentBehavior {
// functionality that exists in RootIndex and SubIndex, which does not
// depend on Index.
}
class ChildBehavior {
// functionality that exists in SubIndex and KPI, which does not depend
// on Index.
}
abstract class Index {
// contains post-construction code.
void foo();
}
class RootIndex extends Index {
ParentBehavior parentBehavior;
}
abstract class AbstractSubIndex extends Index {
// shared code between SubIndex and KPI
ChildBehavior childBehavior;
}
class SubIndex extends AbstractSubIndex {
ParentBehavior parentBehavior;
}
class KPI extends AbstractSubIndex {
// unique functionality for KPI
}
这样,SubIndex
和 KPI
从 AbstractSubIndex
继承了 Index
的基本功能,从而继承了Index
所需的后构造功能无需重复,同时仅具有基类所需的功能(通过 ParentBehavior
和 ChildBehavior
)。
关于java - 解决 Java 中的多重继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25183340/