我发现自己反复用“单元”对象的二维数组制作一个“矩阵”类(我的标题中的“依赖”类,不确定是否有一个标准术语,一个外部的类,但只能从调用其构造函数和方法的类)。所以当然,我希望自己构建一些可重用的类和/或接口。
矩阵如下所示:
public class Matrix {
private Cell matrix[][];
private float spaceWidth, spaceHeight;
private int xCols, yRows;
public Matrix(int xCols, int yRows, float width, float height){
matrix = populateCells(xCols,yRows);
spaceWidth = width / xCols;
spaceHeight = height / yRows;
this.xCols = xCols;
this.yRows = yRows;
}
public Cell[][] populateCells(int xCols, int yRows) {
Cell c[][] = new Cell[xCols][yRows];
int k = 0;
for (int i = 0; i < xCols; i++){
for(int j = 0; j < yRows; j++){
c[i][j] = new Cell(i,j,k);
k++;
}
}
return c;
}
...
}
public class Cell {
private int x, y, num;
public Cell(int x, int y, int num, String name){
this.x = x;
this.y = y;
this.num = num;
}
public float getX(){return x;}
public float getY(){return y;}
public int getNum(){return num;}
}
我希望每个 Cell 和每个 Matrix 都具有这些属性。当我想扩展 Cell 以添加属性时,问题就来了。无论我尝试什么接口和/或抽象的组合,我似乎都无法弄清楚如何在不逐字重写 Matrix.populateCells 的情况下扩展 Matrix 和 Cell,只使用新的 Cell 名称。换句话说,我想在不破坏 Matrix 中对它的每个引用的情况下扩展 Cell。
所以基本上,我如何组织它以便抽象做它应该做的事情,即限制重复代码、封装等?
总结一下我对所选答案的实现:
public interface ICell {
public abstract int getX();
public abstract int getY();
public abstract int getNum();
}
public class Cell implements ICell {
private int x, y, num;
public Cell(int x, int y, int num){
this.x = x;
this.y = y;
this.num = num;
}
//getters...
}
public class WaveCell extends Cell implements ICell {
private boolean marked;
public WaveCell(int x, int y, int num) {
super(x, y, num);
marked = false;
}
public boolean isMarked() {return marked;}
public void setMarked(boolean marked) {this.marked = marked;}
// More new stuff...
}
public class WaveMatrix extends Matrix {
public WaveMatrix(int xCols, int yRows, float width, float height) {
super(xCols, yRows, width, height);
}
@Override
public ICell newCell(int i, int j, int k){
ICell c = new WaveCell(i,j,k);
return c;
}
...
}
public class Matrix {
private ICell matrix[][];
private float spaceWidth, spaceHeight;
int xCols, yRows;
public Matrix(int xCols, int yRows, float width, float height){
matrix = populateCells(xCols,yRows);
spaceWidth = width / xCols;
spaceHeight = height / yRows;
this.xCols = xCols;
this.yRows = yRows;
}
public ICell[][] populateCells(int xCols, int yRows) {
ICell c[][] = new ICell[xCols][yRows];
int k = 0;
for (int i = 0; i < xCols; i++){
for(int j = 0; j < yRows; j++){
c[i][j] = newCell(i,j,k);
k++;
}
}
return c;
}
public ICell newCell(int i, int j, int k){
ICell c = new Cell(i,j,k);
return c;
}
...
}