public MyClass(Integer userId, Integer otherId) {
if(!userId.equals(otherId)){
this.userId = userId;
this.otherId = otherId;
}
}
這就是我得到,我想確保一個實例,如果從來沒有創建與匹配的ID?構造函數需要兩個整數,它們不能相等,最好的實現方法是什麼?
public MyClass(Integer userId, Integer otherId) {
if(!userId.equals(otherId)){
this.userId = userId;
this.otherId = otherId;
}
}
這就是我得到,我想確保一個實例,如果從來沒有創建與匹配的ID?構造函數需要兩個整數,它們不能相等,最好的實現方法是什麼?
我創造了另一個方法和取得的構造私人,如果匹配ID
private MyClass(Integer userId, Integer otherId) {
{
this.userId = userId;
this.otherId = otherId;
}
}
public static MyClass getInstance(Integer userId, Integer otherId)
if(!userId.equals(otherId)){
return new MyClass(userId,otherId);
}
return null;
}
如果你不能讓這兩個值相等,那麼你在這種情況下唯一的選擇就是引發異常。
我用另一種方法,我把新創建的實例的註冊表(在HashSet的),並允許對象instatiation它返回null通過一個靜態工廠。
class User {
private int _id;
private static HashSet _instanced = new HashSet();
public static User getInstance(Integer id) {
if (_instanced.contains(id)) {
return null;
}
return new User(id);
}
private User(Integer id) {
_id = id.toInt();
}
// Getter/Setter for ID
}
由於構造函數是私有的,沒有一個會實例化具有相同ID的另一個用戶。
在你的方法,你可以接着寫
User x = User.getInstance(1);
當然會多一個層次添加到您的解決方案。不過我更喜歡這種方法。
我可能完全忽略了你的設計,但是如果你想創建一個具有永不衝突的唯一ID對象的實例,請考慮使用UUID。你的實例永遠不需要做ID比較的「圈地混亂」,以確保它們沒有違反唯一性約束。
+1「ID比較的圓形混亂」 - **有**是第一次這些單詞共享一個句子! – millhouse
看起來像是一個巨大的內存泄漏等待發生在我身上 - 而且是線程問題的根源。我會敦促OP *不*這樣做,除非他們肯定需要。 –
我同意,當在User類中添加一個Dispose()時,必須清理不再需要的項目(java沒有析構函數,所以你必須自己管理這些東西)。在網絡應用中使用了類似的東西,周圍沒有太多數據。如果數字變高,我更願意在db PK中檢查並管理重複的插入異常。從這個角度來看,Nim的答案與往常一樣,要好得多。 PS:對於短缺我已經省略了syncro的東西:) – BigMike