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