我正在编写一个 Java 国际象棋游戏,并且正在尝试整理设计。到目前为止,这是我的类(class):
游戏:由 2 个玩家对象和一个棋盘对象组成
玩家:
棋盘:由方形对象的二维数组 (8 x 8) 组成,每个对象上可能有/可能没有棋子
国王、王后、车、主教、骑士、兵:
片段:上述片段的父类(super class),共享功能在这里
以下是我不喜欢的地方:我的 Square 类中有一个名为“board”的字段,因此我可以引用给定方 block 所属的棋盘。我不喜欢这种设计,因为它会导致克隆问题。
所以我想在不进行这种回溯的情况下重写 piece 类中的一些功能。板能够访问它的每个方 block 是很好的,但我不希望 Square 类有 getBoard() 函数。
这是我需要重写的函数示例:
public Square getSquareOneMoveAway(Square start, int heightChange, int widthChange) {
Square candidateSquare = start.getBoard().getNearbySquare(start, heightChange, widthChange);
if (candidateSquare != null) {
if (candidateSquare.isEmpty()) {
return candidateSquare;
} else if (! candidateSquare.getPiece().getColor().equals(start.getPiece().getColor())) {
return candidateSquare;
}
else {
return null;
}
}
else {
return null;
}
}
请注意,在我的 Player 类中,我有如下方法:
canMovePiece(Square start, Square end, Board board), movePiece(Square start, Square end, Board板)等
我是否应该将此方法移动到 Board 类中,这样我就可以访问 board 对象而无需从 Square 转到 board?
非常感谢任何想法, 布莱曼
最佳答案
在我看来,您对问题的设计过度了。用另一个类来表示棋盘的方 block 真的有什么好处吗?如果不是(我不这么认为),我会摆脱 Square 类。
class Board {
public static final int MAX_ROWS = 8;
public static final int MAX_COLS = 8;
private Piece[][] squares;
public Board() {
squares = new Piece[ MAX_ROWS ][ MAX_COLS ];
}
// ...
}
不过,我有一个 Position 类,包含一对行和一列。
希望这对您有所帮助。
关于java - OOP 设计以两种方式避免对象另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31642643/