私は自分のプロジェクトに と呼ばれる機能的インターフェースを定義しましたFunction
。call
次のように、メソッドは 1 つだけです。
public interface Function {
public void call();
}
そして、私の Field オブジェクトには、これがあります:
public class Field {
private Square[][] matrix; //Square is dispensable.
public Field(int rows, int cols) {
matrix = new Square[rows][cols];
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
this.matrix = new Square(i * Square.NORMAL_WIDTH, j * Square.NORMAL_HEIGHT);
}
}
}
}
これは正常に動作し、JavaScript に似ていますが、注意を向けているオブジェクトを渡すことができません。しかし、私はこの方法を開発したいと考えています:
public void each(Function f){
int rows = matrix.length;
for(int i = 0; i < rows; i++){
int cols = matrix[i].length;
for(int j = 0; j < cols; j++){
f.call();
}
}
}
特定のコード (この場合は Function の実装) をマトリックスのすべての要素にアタッチします。そうすれば、そのプロパティにアクセスできます。しかし、行列のすべてのオブジェクトは正方形です。どうすればアクセスできますか? 私はそれを関数に渡すことができました、
//making an small alteration to the parameter.
public interface Function {
public void call(Square square);
}
public void each(Function f){
int rows = matrix.length;
for(int i = 0; i < rows; i++){
int cols = matrix[i].length;
for(int j = 0; j < cols; j++){
f.call(matrix[i][j]);
}
}
}
それでも、私はSquare
タイプにとらわれます。ジェネリック型を使用できますか?