当我们尝试通过继承重用代码时如何解决并行继承层次结构
最近在一次求职面试中,他们问我“当我们尝试通过继承重用代码时如何解决并行继承层次结构”。我想到了聚合或组合,但我对基于此做一个例子感到有点困惑。
所以我决定留待以后加深概念,但经过调查后并没有最终形成该问题的精确答案,有人可以向我解释一个解决方案或一个例子吗?
Recently in a job interview, they ask me "how to solve Parallel Inheritance Hierarchies when we try to reuse code through inheritance". I thought on Aggregation or Composition, but i was a little confused on making an example based on that.
So I decided to leave it pending to deepen concepts later, but after investigating it did not end up forming a precise answer to that question, could someone explain me a solution or an example to this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
并行继承层次结构产生了许多不必要的类,并使代码非常脆弱且紧密耦合。
例如,我们有类
Sportsman
及其Goal
。和具体类
Footballer
:和
Runner
:那么我们就有了他们的目标:
及其具体类:
和跑步者目标:
现在,可以看出,如果我们添加新类型运动员,那么我们需要在
Goal
的层次结构中添加一个新类。我们可以尝试通过使用依赖注入和提取接口方法来避免创建层次结构树。
首先,我们创建接口:
然后实现它:
并在
Footballer
类中使用它:现在我们没有层次结构树,我们可以这样调用它:
更新:
有一篇关于并行继承的好文章层次结构。。它提出了一些解决此任务的方法。让我展示第三种方法。
所以
Footballer
类会像这样:而
Runner
类会像这样:Parallel Inheritance Hierarchies makes many unnecessary classes and makes code very fragile and tightly coupled.
For example, we have class
Sportsman
and itsGoal
's.and concrete class
Footballer
:and
Runner
:Then we have their goals:
and its concrete classes:
And runner goal:
Now, it can be seen that if we add new type of sportsman, then we need add a new class to hierarchy of
Goal
.We can try to avoid of creation of that hierarchy tree by using dependency injection and extracting method to interface.
At first, we create interface:
and then just implement it:
and use it in
Footballer
class:Now we do not have hierarchy tree and we can call it like this:
UPDATE:
There is a good article about Parallel Inheritance Hierarchies.. It proposes some ways to solve this task. Let me show the third way.
So
Footballer
class would like this:And
Runner
class would like this:c2 wiki 有一个关于并行继承层次结构的页面,其中 ChaoKuoLin 列出了四个可能的解决方案。我在这里对它们进行了解释,并为每个内容提供了一些背景信息。请参阅原始页面以获取完整的说明,包括优点、缺点和示例。
wiki 中建议的另一个解决方案是 Mix In 并且在 如何解决UI案例中的并行继承?
The c2 wiki has a page on parallel inheritance hierarchies where ChaoKuoLin lists four possible solutions. I paraphrase them here, along with some context for each. See the original page for a full explanation including advantages, disadvantages, and examples.
Another solution suggested in the wiki is Mix In and it is also suggested in How to solve parallel Inheritance in UI case?