我认为这是一个小问题,甚至可能是主观的,但它确实困扰着我。每当我创建由单元格网格组成的东西(主要是游戏)时。我倾向于对单元格和网格使用相同的 setter/getter 。为了解释清楚,这里有代码示例:
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;
}
}
这是我的网格类:
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
}
我不知道。我可能想太多了,这可能是一个愚蠢的问题,但是,有更好的方法吗?也许只有我一个人,但我觉得它有点笨拙,而且有很多额外的代码。这个设计好吗?
最佳答案
我会将 Edwin 的 Grid
类更改为这样的接口(interface):
public interface Grid {
public void setValue(String value, int row, int column);
public String getValue(int row, int column);
}
CellGrid
类使用 Cell
的二维数组实现 Grid
:
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();
}
}
您的 Cell
类基本保持不变,只是我将 value1
的类型从 int
更改为 String
:
class Cell {
private String value;
// other fields can go here
public Cell(String value, ...){
this.value = value;
// ...
}
public String getValue(){
return value;
}
}
您可以使用以下代码访问单元格的特定属性:
grid.getValue(2, 2)
并不是说当您进行此调用时,您不需要了解有关Grid
实现的任何信息。正如我在最初的回答中提到的,CellGrid
类对其 Cell
的内部工作没有任何依赖。
关于java - OOP设计问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292682/