长继承层次 [英] Long inheritance hierarchy
问题描述
我有很长的类继承层次结构.例如:
I have very long class inheritance hierarchy. For example:
-MyAbstractObject
--MyAbstractUiObject
---MyAbstractTable
-----MyAbstractPageableTable
-------MyAbstractScrollableTable
---------MyAbstractStateblaTable
等等...
我在 Code complete
读到理想的继承深度是 3.有时允许继承深度为 7-9.但是我有传承深11!
I read at Code complete
that ideal inheritance deep is 3. And sometimes it allowable to make inheritance deep 7-9. But I have inheritance deep 11!
如何更改我的架构?什么设计模式适用于我的案例?不好的是,我可以更改继承层次结构中 MyAbstractPageableTable
和 MyAbstractScrollableTable
的位置.这 2 个类没有混为一个,因为我的目标是单一职责.我也想为用户提供不同的接口(API)
How I can change my architecture? What design pattern is applicable to my case? And what is bad is that I can change places of MyAbstractPageableTable
and MyAbstractScrollableTable
in inheritance hierarchy. This 2 classes not mixed into one because my goal is single responsibility. Also I want to provide for users different interfaces (APIs)
推荐答案
通常最好使用策略模式而不是为每个用例创建子类.但很难给出任何硬性建议,因为这取决于具体情况.
Often it is better to use a Strategy-Pattern and not create an Subclass for each use case. But it is hard to give any hard advice because it depends on the circumstances.
在你的例子中,我猜你可以做一个表格实现并给它一个策略对象来处理例如分页或表格应该支持的任何其他显示策略.
In your example I would guess you could do a Table Implementation and give it an strategy-object that handles for example the Pagenation or any other display strategy the table should support.
根据 Joshua Bloch 的Effective Java",通常使用组合优于继承.我不认为更大的继承深度是坏的,只要它们保持可以理解,有 11 个级别我猜不是这样.
According to Joshua Bloch's "Effective Java" it is often better to use composition over inheritence. I don't think larger inheritence depths are bad, as long as they stay understandable, with 11 levels I would guess thats not the case.
这篇关于长继承层次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!