以下是基本的构建器模式
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("123@abc.com").type(AccountType.PREMIUM).image("abc.png").builder();
就像
type
方法调用之后,如果它是高级帐户,那么我可以进行image
方法调用。它给我一个错误,因为它无法识别和找到图像方法。我不确定这是否是正确的方法,还是有更好的方法?
最佳答案
accountType
返回类型为Builder
的对象,该对象没有image
方法。可能的解决方案是将image
方法添加到Builder
类中,而该类只忽略Image
,然后当PremiumBuilder
的image
方法可以对;另一种方法是将Image
传递给Image
方法,然后负责将accountType
传递给Image
的构造函数