我为我的项目定义了一个名为Function
的功能界面。它只有一个方法,call
,像这样:制作功能界面,使用不同的对象类型
public interface Function {
public void call();
}
而且在我的领域对象,我有这样的:
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();
}
}
}
这将附加一定的一段代码(在这种情况下,功能实现),以矩阵的每个元素。这样,我可以访问它的属性。 但矩阵的每个对象都是一个正方形。我怎样才能访问它?我可以把它的功能,
//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
类型。也许我可以使用泛型类型?
...是的,仿制药是你如何解决这个问题? –
你可能最好不要把Java变成JavaScript。 – Raedwald
猜你是对的。但是,它是一个有用的界面,但。也许我可以在项目的其他部分使用它。 – thepanuto