2013-07-24 155 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