以下是基本的构建器模式

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,然后当PremiumBuilderimage方法可以对;另一种方法是将Image传递给Image方法,然后负责将accountType传递给Image的构造函数

07-24 19:09
查看更多