[英]What to do with fields that can only be assigned non-null values after the object is created (Java)
假設我正在做一個游戲:
public class Game {
Board board;
public ArrayDeque<Player> players;
//Players can have 'knights' and the one with the largest number
//is referenced by the game.
public Player playerWithLargestArmy;
...
}
在一開始,像這樣的游戲初始化時,沒有玩家可以擁有最大的軍隊(玩家只有一定數量的騎士后,才擁有“軍隊”)。 我想為playerWithLargestArmy分配一個值,但是我不確定。 我也不想使用null
因為我可以留下隱式賦值來做到這一點(而且無論如何,使用null都是不好的做法)。
我正在尋找可以向我解釋如何解決此問題的人。 我查找了工廠和建築商,但不確定他們是否會處理這種延遲的任務。 對於上下文,每個玩家都有一個int字段,用於指定他們擁有多少個騎士。
我可以用一個布爾值來解決這個問題,每個布爾值都說明他們是否擁有最大的軍隊,但隨后您需要遍歷這些球員以找到該球員,這並不理想。 就我而言,即使這不是一個巨大的犧牲,我仍然想知道以供將來參考。
對於這種情況,有java.util.Optional<T>
類。
它具有isPresent()
和get()
(以及其他幾種方法),使您能夠檢查對象是否存在並獲取基礎對象的實例。
例子
宣言
Optional<Player> playerWithLargestArmy = Optional.empty();
價值分配
playerWithLargestArmy = Optional.of(newValue);
價值用途
if(playerWithLargestArmy.isPresent()) {
Player p = playerWithLargestArmy.get();
}
甚至更好
playerWithLargestArmy.map(p -> doSomethingWithIt(p));
僅在存在值的情況下才會調用doSomethingWithIt
。
空對象模式https://en.wikipedia.org/wiki/Null_Object_pattern
public class Army {
public static final Army NullArmy = new Army(0);
private int size;
public Army(int size) {
this.size = size;
}
}
現在,當您創建新的Army時,只需將初始值設置為Army.NullArmy。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.