java - 继承层次结构改变以减少代码重复

标签 java generics inheritance hierarchy

我在设置代码结构时遇到困难。在一个项目中,我有两个类 LeftCellRightCell,它们都扩展了类 Cell。现在,为了避免代码重复,我想在多个其他项目中使用这些对象。问题是我还想为这些对象(特别是 Cell 对象)添加额外的功能,这些功能因项目而异。

假设我创建了一个新项目,我想在其中使用 void draw() 方法可视化 Cell 对象。我的第一个想法是创建一个新的 CellProject1 类来扩展 Cell 类并包含 draw() 方法:

class CellProject1 extends Cell {
    void draw() {}
}

问题是我创建的任何 LeftCell/RightCell 对象当然无法访问此 draw() 方法。我想我想以某种方式压缩类层次结构中的 Cell 子类,使其从以下位置更改:

Cell
    LeftCell
    RightCell

到:

Cell
    CellProjectX
        LeftCell
        RightCell

取决于我正在运行的项目。我玩过泛型,但无法让它发挥作用。欢迎所有建议!

最佳答案

The problem is that any LeftCell/RightCell objects I create, do of course not have access to this draw() method.

子类的特定方法当然不能在不知道它的父实例上调用。

因为你的要求是

Inheritance hierarchy altering to reduce code duplication In one project, I have two classes LeftCell and RightCell, both extending class Cell. Now, to avoid code duplication, I want to use these objects in multiple other projects

我认为你应该做一些不同的事情。

如果你想避免类的可能组合数量激增并且不像你的示例那样复制 LeftCellRightCell :

Cell
    CellProjectX
        LeftCell
        RightCell

最终可以完成:

Cell
    CellProjectY
        LeftCell
        RightCell

Cell
    CellProjectZ
        LeftCell
        RightCell

您应该更喜欢组合而不是继承来创建您的特定项目 Cell 实现。

对于常见的 Cell 结构:

Cell 子类可以是一个 Cell 接口(interface),它为任何 Cell 定义通用方法,您可以有一个 AbstractCell 类,为其定义通用实现。

public interface Cell{
   int getValue();
   void setValue(int value);
}


public abstract class AbstractCell implements Cell{
      ...
}

然后您可以通过扩展 AbstractCell 来定义 RightCellLeftCell :

public class RightCell extends AbstractCell {
      ...
}

public class LeftCell extends AbstractCell {
      ...
}

对于特定于项目的 Cell 实现:

现在,在特定项目中,您可以通过将其与 Cell 实例(最后是 LeftCellRightCell 实例)将在引擎盖下用于在特定项目具体类中实现 Cell 接口(interface)。
在具体实现中,您当然可以根据项目的具体情况添加任何需要的方法。
例如:

class CellProject1 implements Cell {

   private Cell cell;

   CellProject1 (Cell cell){
      this.cell = cell;
   }

   public int getValue(){
      cell.getValue();
   } 

   public void setValue(int value){
      cell.setValue(value);
   }

   public void draw(){
   ...
   }

}

您可以这样创建 CellProject1 实例:

CellProject1 leftCell = new CellProject1(new LeftCell());
CellProject1 rightCell = new CellProject1(new RightCell());
leftCell.draw();
rightCell.draw();

在另一个使用具有特定write()方法的CellProject2实例的项目中,您可以这样写:

CellProject2 leftCell = new CellProject2(new LeftCell());
CellProject2 rightCell = new CellProject2(new RightCell());
leftCell.write();
rightCell.write();

关于java - 继承层次结构改变以减少代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43768505/

相关文章:

Java - 将 xml 对象转换为字符串

使用 AES 加密的 Java GUI 程序

java - 使用 RSA 解密时收到错误

java - 编译警告 : Unchecked call to XXX as member of the raw type

java - 在 new 关键字后省略通用参数

java - 子类需要无参构造函数,但父类(super class)没有

java - java中的getter setter作用域

java - 本例中处理多态性的正确方法(JAVA)

c# - 非常奇怪的 C# 泛型问题

java - Java中synchronized是继承的吗?