以下是基本的构建器模式
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
方法调用。
它给了我一个错误,因为它无法识别和找到图像方法。我不确定这是否是正确的方法,还是有更好的方法?