2013-07-24 104 views
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方法调用之后。

它给我一个错误,因为它无法识别并找到图像方法。我不确定这是否是正确的做法,还是有更好的方法来做到这一点?

回答

1

accountType返回Builder类型的对象,该对象没有image方法。一种可能的解决方案是将image方法添加到仅忽略ImageBuilder类中,然后PremiumBuilderimage方法替代image方法时可以对Image做一些有用的操作;另一种是将Image传递到accountType方法,它是将负责传递ImagePremiumBuilder的构造

+0

但如果它是基本账户,我不想图像的选项调用... – peter

+0

@ user1389813在这种情况下,将'Image'传递给重载的'accountType'方法;或者在'AccountType'类中包含'Image'作为字段或方法,以便'accountType'方法可以检索它并将其传递给'PremiumBuilder'构造函数 –

+0

你是否意味着通过重载accountType方法?在这种情况下,你如何设置图像? – peter