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)
如果只能通過工廠方法創建超類,那麼只能通過工廠方法創建子類。因爲子類的成員是超類的成員。 –