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)
如果只能通过工厂方法创建超类,那么只能通过工厂方法创建子类。因为子类的成员是超类的成员。 –