簡體   English   中英

覆蓋父類的List類型,以避免在調用方法時進行強制轉換

[英]Overwriting the List type of the parent class to avoid casting when calling methods

我有一個輸入文件(text => TextFileImporter或xml => XmlFileImporter ),其中包含具有不同結構的數據。 Definiton類中描述了一種結構,因此我的FileImporter對象保存了Definition多個實例。

TextFileImporter應該包含List<TextDefinition>XmlFileImporter應該包含List<XmlDefinition>

請看一下示例代碼:

// Parent classes
abstract class Definition {}

abstract class FileImporter {
  protected List<Definition> definitions;

  public FileImporter(List<Definition> definitions) {
    this.definitions = definitions;
  }

  public void doSomething() {
    // use 'definitions'
  }
}

// Text files
class TextDefinition extends Definition {
  public void copyLine() {}
}

class TextFileImporter extends FileImporter {
  // here should be clear that 'definitions' is of type List<TextDefinition>
  // to call 'copyLine()' on its items
}

// XML files
class XmlDefinition extends Definition {
  public void copyNode() {}
}

class XmlFileImporter extends FileImporter {
  // here should be clear that 'definitions' is of type List<XmlDefinition>
  // to call 'copyNode()' on its items
}

如您所見,基於這些評論,我不確定如何更好地處理該問題。 當然我首先需要構造函數。 然后,我不想每次都將definitions每個項目都definitions轉換為合適的子類,僅是為了調用方法。

我可以在這里合理使用泛型嗎? 還是有其他解決方案?

您必須引入一些泛型。

// Parent classes
abstract class Definition {}

abstract class FileImporter<T extends Definition> {
  protected List<T> definitions;

  public FileImporter(List<T> definitions) {
    this.definitions = definitions;
  }

  public void doSomething() {
    // use 'definitions'
  }
}

// Text files
class TextDefinition extends Definition {
  public void copyLine() {}
}

class TextFileImporter extends FileImporter<TextDefinition> {
  // here should be clear that 'definitions' is of type List<TextDefinition>
  // to call 'copyLine()' on its items
}

// XML files
class XmlDefinition extends Definition {
  public void copyNode() {}
}

class XmlFileImporter extends FileImporter<XmlDefinition> {
  // here should be clear that 'definitions' is of type List<XmlDefinition>
  // to call 'copyNode()' on its items
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM