有条件地从类继承 [英] Conditionally inherit from class

查看:95
本文介绍了有条件地从类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下类继承(A是我的父类):

I have following class inheritances (A is my parent class):

在某些情况下XY需要一些额外的字段和方法.所以我基本上需要的是这样:

In some cases, X and Y need some extra fields and methods. So what I basically need is this:

由于重复的代码,我不想扩展XY为其子类提供完全相同的字段和方法.
如何处理呢?唯一的解决方案是代表吗?

I don't want to extend X and Y to give their child classes exact the same fields and methods due to duplicate code.
How to handle this? Is the only solution a delegate?

更新:真实示例:

我要从不同的文件类型导入数据:

I'm importing data from different file types:

软件包 my_application.core :

public class ImportFile { // the "A"
  protected final Path path;
}

public class CsvImportFile extends ImportFile { // the "X"
  private final String delimiter;
}

public class FixedLengthImportFile extends ImportFile { // the "Y"
  // nothing new
}

public class XmlImportFile extends ImportFile {
  private final String root;
}

有时文件的第一行包含标题/标题而不是数据.因此,这里有一个示例扩展,它允许为csv和定长文件设置起始行:

Sometimes the first lines of a file contain heads/titles instead of data. So here an example extension which allows to set a start line for csv and fixed-length files:

软件包 my_application.extension.line_start :

public class ExtensionLineStartImportFile { // the "B"
  protected final int lineStart;
  // some methods
}

因此,如果用户选择使用扩展名 line_start ,则CsvImportFileFixedLengthImportFile应该会获得ExtensionLineStartImportFile的属性.

So if the user chooses to use the extension line_start, CsvImportFile and FixedLengthImportFile should get the properties of ExtensionLineStartImportFile.

侧节点:由于我有多个扩展来执行不同的操作,并且这些扩展应该易于添加到应用程序中或从应用程序中删除,所以我不想将它们全部合并到核心"中.

Side node: Since I have multiple extensions which do different things and these extensions should be easy to add to/remove from the application, I don't want to merge them all into the "core".

推荐答案

工厂模式-此这是一个架构性问题,这种模式应该可以解决您的问题

Factory pattern - this is quite an architectural issue and this pattern should be the answer for Your problem

这篇关于有条件地从类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆