「Cell」オブジェクトの2D配列を持つ「Matrix」クラスを繰り返し作成していることに気づきました(私のタイトルの「依存」クラス、これに標準的な用語があるかどうかはわかりません。外部であるが、からのみアクセスされるクラス)コンストラクターとメソッドを呼び出すクラス)。もちろん、再利用可能なクラスやインターフェースを自分で構築したいと考えています。
マトリックスは次のようになります。
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.populateCells を逐語的に書き換えずに Matrix と 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;
}
...
}