[英]Java Constructor issue - boolean condition
我試圖在構造函數中放置布爾條件。
任務是僅在條件為真時創建對象。
在下面的示例中:如果checkInitialPass()
返回 false,則不應創建對象。
SecuredNotepad(int numPages) {
super(numPages);
checkInitialPass();
}
那是不可能的。
您(至少)有兩個選擇:
SecuredNotepad(int numPages) {
super(numPages);
if (!checkInitialPass()) {
throw new IllegalArgumentException("Invalid");
}
}
將構造函數設為私有並創建靜態工廠方法。
private SecuredNotepad(int numPages) {
super(numPages);
}
public static SecuredNotepad createInstance(int numPages) {
if (checkInitialPass()) {
return new SecuredNotepad(numPages);
}
else {
return null;
// Or throw exception
}
}
如果初始傳遞失敗,我會選擇工廠方法,該方法會引發異常。 或者,如果您想進一步擴展它,您可以使用SecureNotepadFactory
,正如 Thomas Timbul 在評論中提到的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.