0
以下是基本構建器圖案動態生成器模式
enum AccountType {
BASIC,PREMIUM;
}
class AccountBuilder {
private AccountBuilder(Builder builder) {}
private static class PremiumAccountBuilder extends Builder {
public PremiumAccountBuilder() {
this.canPost = true;
}
public PremiumAccountBuilder image(Image image) {
this.image = image;
}
}
public static class Builder {
protected String username;
protected String email;
protected AccountType type;
protected boolean canPost = false;
protected Image image;
public Builder username(String username) {
this.username = username;
return this;
}
public Builder email(String email) {
this.email = email;
return this;
}
public Builder accountType(AccountType type) {
this.type = type;
return (this.type == AccountType.BASIC) ?
this : new PremiumAccountBuilder();
}
public Account builder() {
return new Account (this.name,this.email,this.type, this.canPost, this.image);
}
}
}
所以高級帳戶基本上覆蓋canPost並且可以設置圖像。
我不知道我是否可以這樣做
Account premium = new AccountBuilder.Builder().username("123").email("[email protected]").type(AccountType.PREMIUM).image("abc.png").builder();
一樣,如果它是一個溢價賬的話,我可以能夠使image
方法調用type
方法調用之後。
它給我一個錯誤,因爲它無法識別並找到圖像方法。我不確定這是否是正確的做法,還是有更好的方法來做到這一點?
但如果它是基本賬戶,我不想圖像的選項調用... – peter
@ user1389813在這種情況下,將'Image'傳遞給重載的'accountType'方法;或者在'AccountType'類中包含'Image'作爲字段或方法,以便'accountType'方法可以檢索它並將其傳遞給'PremiumBuilder'構造函數 –
你是否意味着通過重載accountType方法?在這種情況下,你如何設置圖像? – peter