我寫了下面的類和相應的同伴對象:斯卡拉工廠模式提高了設計
class Tile(val tileCoordinate: Int, val pieceOnTile: Piece) {
override def toString(): String = {
if(isOccupied()) {
pieceOnTile.toString()
}
"-"
}
def isOccupied(): Boolean = pieceOnTile != null
}
object Tile {
def apply(coordinate: Int, piece: Piece): Tile = {
new Tile(coordinate, piece)
}
def apply(coordinate: Int): Tile = {
new Tile(coordinate, ??) // what is the best design here?An Option?
}
}
我的問題是,當工廠方法沒有piece
它被調用創建一個Tile
,什麼是適當的參數傳遞給Tile
構造函數?我不想通過null
,這似乎是一個糟糕的設計選擇。我是否應該讓主構造參加Option[Piece]
並通過None
?
這似乎有點太醜陋,因爲當我想創建一個瓦我需要說:
val t = Tile(1, Some(new Knight()));
案例類看起來像最乾淨的方法,謝謝 –
你可以有一個案例類,並添加一個額外的工廠方法嗎? –
@AmirAfghani,是的,你可以。只需爲該類定義一個伴隨對象並向其添加方法即可。不過,這些方法不應該與編譯器生成的方法衝突。 –