gpt4 book ai didi

java - 类的构造函数,其 super 只能通过工厂方法创建

转载 作者:行者123 更新时间:2023-12-01 08:58:00 26 4
gpt4 key购买 nike

我有以下类(class):

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
}
}

但现在我陷入困境了。 Bar 的构造函数必须以某种方式调用 super(),但这不会像 Foo.Factory() 那样检查重复项。

我真正想要的是这样的:

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

但这显然不是有效的 java。

现在,我被迫为 Foo 编写一个 hacky 辅助构造函数,它还检查重复项,并让 Bar 使用它:

//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:如何为一个类创建一个构造函数,该类的 super 只能通过工厂方法创建。

可能与 this question 重复,但是在java中(这个问题只有一个答案,我和OP都不满意)

最佳答案

在我看来,你有两个选择。

选项 1 是为 bar 创建一个工厂方法,而不是公共(public)构造函数。

选项 2 是,不是让 bar 继承自 foo,而是包含 foo 的实例作为成员。在构造函数中,您可以调用 foo 的工厂方法。

你走哪条路可能取决于细节。

关于java - 类的构造函数,其 super 只能通过工厂方法创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41904506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com