我正在開發一個專案(游戲),該專案將有一塊板子可以玩。
我想讓這個板盡可能通用,以便能夠將代碼重用于可能的其他游戲。
public class Board {
private int rows;
private int cols;
private Box[][] board;
public Board(int rows, int cols){
Box[][] board = new Box[rows][cols];
for (int row = 0; row < this.rows; row ){
for (int col = 0; col < this.cols; col ){
board[row][col] = new Box();
}
}
}
public int getCols(){return this.cols;}
public int getRows(){return this.rows;}
public Piece getContentAtPos(int row, int col){
return board[row][col].getContent();
}
}
這是Board課堂。這里的問題是我必須使用該方法回傳一個Piece物件,getContentAtPos()因為Box( Cell ) 類是這樣的:
public class Box {
private boolean empty;
private Piece content;
public Box(){
empty = true;
}
public Box(Piece piece){
empty = false;
this.content = piece;
}
public boolean isEmpty(){
return empty;
}
public Piece getContent(){
if (!empty) {
return content;
} else {
return null;
}
}
}
然而,對我來說,最理想的Box是能夠托管任何型別的物件并getContentAtPos()通過 BoxgetContent()方法回傳這個通用物件的類。
我的通用Box類。
public class Box<T>{
private boolean empty;
private T content;
public Box(){
empty = true;
}
public Box(T content){
this.content = content;
empty = false;
}
public boolean isEmpty(){
return empty;
}
public T getContent(){
if (!isEmpty()){
return content;
}
return null;
}
public T setContent(Object content){
this.content = content;
}
}
但是我需要在 Board 類中進行哪些更改?
我應該放什么回傳值?
uj5u.com熱心網友回復:
對我來說理想的
Box是能夠托管任何型別的物件并getContentAtPos通過BoxgetContent方法回傳這個通用物件的類
我猜你希望你的游戲片段宣告某種行為。如果是這樣,Box則不需要存盤任意物件,而是代表合同的型別的物件,該合同包含游戲片段應具有的所有方法。
換句話說,你可以定義一個介面,比如說Piece,它將有幾個實作:
public interface Piece {
// behavior of game pieces
}
public class MyGamePiece implements Piece {
// implementations
}
您不需要將Box類設為泛型,而是可以包含型別欄位Piece:
public class Box {
private boolean empty;
private Piece content;
// constractor and methods
public void setContent(Object content){
this.content = content;
}
public Piece getContent(){
return content;
}
}
這使您可以自由地提供類的Peicevia 建構式的任何實作Box或真正的 setter。這意味著您可以設計僅具有一個實作的核心部分MyGamePiece,然后添加更多類,例如NewGamePeace(名稱應該反映類的目的,如果清晰簡潔的方式,這只是一個虛擬示例)。
關鍵是您可以從多型性中受益,并且不必更改先前設計和測驗的代碼以使其與新類一起使用(稱為后期系結):
Box box = new Box();
box.setContent(new MyGamePiece());
box.setContent(new NewGamePeace()); // in order to make this line compile only need to introde the `NewGamePeace` class itself
并且方法getContentAtPos()也將回傳一個型別的物件Piece。
我想讓這個板盡可能通用,以便能夠將代碼重用于可能的其他游戲。
這是一個值得稱贊的目標。
你的類必須是松散耦合的并且專注于狹窄的以便可重用。即每個類都應該有一組狹窄且定義明確的功能,并且只知道對其作業至關重要的那些物件(減少耦合)。
并且可以通過引入如上所示的介面,讓必要的耦合變得松散(高耦合不好,但類根本不耦合就無法互動,需要保持平衡)。
即使最終您不會在其他專案中使用此代碼,保持松散耦合也是有益的,因為它更易于維護和擴展代碼。
uj5u.com熱心網友回復:
您應該創建將來回傳的每個類都將實作的介面。這樣,您將確保回傳型別將實作介面并具有定義的行為。
public interface ReturnableBox {
public boolean isEmpty();
}
public class Board {
private int rows;
private int cols;
private ReturnableBox [][] board;
}
public class Box implements ReturnableBox {
//...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/480204.html
上一篇:多種型別的重用擴展
