OOP设计问题

use*_*x01 2 java oop

我认为这是一个小问题,甚至可能是主观的,但它确实困扰我.每当我创建一些由大量网格组成的东西(主要是游戏).我倾向于为细胞和网格提供相同的吸气剂.为了清楚地解释,这里是代码示例:

class Cell{
    private int value1;
    private boolean value2;

    public Cell(int value1, boolean value2){
        this.value1 = value1;
        this.value2 = value2;
    }

    public int getValue1(){
        return value1;
    }

    public boolean getValue2{
        return value2;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的网格类:

class Grid{
    private Cell[][] cells;

    public Grid(int rows, int cols){
        cells = new Cell[rows][cols];
        // initialize
    }

    public int getCellValue1(int row, int col){
        return cells[row][col].getValue1();
    }

    public boolean getCellValue2(int row, int col){
        return cells[row][col].getValue2();
    }

    // setters, same idea
}
Run Code Online (Sandbox Code Playgroud)

我不知道.我可能会过度思考问题,这可能是一个愚蠢的问题,但是,有没有更好的方法呢?也许这只是我,但我觉得它有点笨重,还有很多额外的代码.这个设计好吗?

Tim*_*sen 5

我会将Edwin的Grid类更改为这样的界面:

public interface Grid {
    public void setValue(String value, int row, int column);
    public String getValue(int row, int column);
}
Run Code Online (Sandbox Code Playgroud)

所述CellGrid类实现一个Grid使用的二维阵列CellS:

class CellGrid implements Grid {
    private Cell[][] cells;

    public CellGrid(int rows, int cols){
        cells = new Cell[rows][cols];
        // initialize
    }

    // get a value using the implementation we chose
    public String getValue(int row, int col) {
        return cells[row][col].getValue();
    }
}
Run Code Online (Sandbox Code Playgroud)

你的Cell类基本未变,但我改变的类型value1intString:

class Cell {
    private String value;
    // other fields can go here

    public Cell(String value, ...){
        this.value = value;
        // ...
    }

    public String getValue(){
        return value;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用以下代码访问单元格的特定属性:

grid.getValue(2, 2)

并不是说当你打这个电话时,你不需要知道任何关于它的实现Grid.正如我在原始答案中提到的那样,CellGrid该类对其内部工作没有任何依赖性Cell.