2017-01-27 56 views
0

進行我有下面的類:構造一類,其超只能通過工廠方法

public class Foo(){ 
    int parameter; 
    static Set<Foo> cache=new HashSet<Foo>(); 
    public Foo(int parameter){ 
     this.parameter=parameter; 
     addToCache(this); 
    } 
    public static Foo Factory(int parameter){ 
     Foo duplicate=findDuplicate(parameter); 
     if (duplicate!=null){ 
      return duplicate; 
     }else{ 
      return new Foo(parameter); 
     } 
    } 
} 

注意,調用Foo的構造將直接加入到靜態緩存。 我現在需要繼承這個對象來添加一些功能。

public class Bar() extends Foo{ 
    public Bar(int parameter){ 
     //Danger 
    } 
} 

但現在我卡住了。酒吧的構造函數必須以某種方式致電super(),但不會檢查像Foo.Factory()這樣的重複項。

我真的想會是什麼這樣的:

public Bar(int parameter){ 
    this=Foo.Factory(parameter); 
} 

但是,這顯然不是有效的Java。

現在,我已經被迫寫美孚也檢查重複哈克次級構造,並酒吧使用:

//Second unused parameter just so the constructors are different 
public Foo(int parameter, boolean isEvil){ 
    Foo duplicate= findDuplicate(parameter); 
    if (duplicate!=null){ 
     this.copy(duplicate); //Evilly take on all attributes of duplicate 
    }else{ 
     //Now we have to copy the body of the original constructor. 
     //It has to be kept synched forever, and I can't even call it! 
     this.parameter=parameter; 
     addToCache(this); 
    } 
} 

Bar(int parameter){ 
    super(int,true); 
} 

但這始終創建新對象的問題,這可能會導致可變性和散列問題。此外,任何不注意的人都不能說這個構造函數的工作方式不同。

TLDR:如何爲超類只能通過工廠方法創建類的構造函數。

this question可能的複製,但在Java中(也即問題只有一個答案,這是不令人滿意的,以我和OP)

+1

如果只能通過工廠方法創建超類,那麼只能通過工廠方法創建子類。因爲子類的成員是超類的成員。 –

回答

1

我看到它的方式,你有兩個選擇。

選項1是爲bar而不是公共構造函數創建工廠方法。

選項2是,代替使bar繼承自foo,而代之以foo作爲成員的實例。在構造函數中,您可以調用foo的工廠方法。

你走哪條路可能取決於細節。

相關問題