gpt4 book ai didi

java - "Creator"配置继承对象的模式

转载 作者:太空宇宙 更新时间:2023-11-04 10:01:22 24 4
gpt4 key购买 nike

我有以下对象结构:

class Annotation;
class LabelAnnotation: inherits Annotation;
class TextAnnotation: inherits LabelAnnotation;

我想使用“creator”对象对这些对象进行一些初始化(此初始化取决于外部设置,因此我不想在这些对象的构造函数中执行此操作。)

特别是,在创建 LabelAnnotation 时我想做:

fontSize = AppDefaults.fontSize

所以我正在写一个“创建者”:

class LabelAnnotationCreator {
LabelAnnotation create() {
annotation = LabelAnnotation()
annotation.fontSize = AppDefaults.fontSize
return annotation;
}
}

现在,我想创建一个 TextAnnotationCreator。这就是我陷入困境的地方:我无法使用 LabelAnnotationCreator,因为它会创建 LabelAnnotation 的实例,但另一方面,我想从 LabelAnnotationCreator 执行的初始化中受益。

class TextAnnotationCreator {
TextAnnotation create() {
annotation = TextAnnotation()
// I'm stuck here:
// can't do LabelAnnotationCreator().create()… ???
return annotation;
}
}

显然,这不是正确的模式,但我不确定如何找到正确的模式。

谢谢!

最佳答案

你对此有何看法:

class TextAnnotation {
private final int someOtherArgs;
private final int fontSize;

public TextAnnotation(LabelAnnotation labelAnnotation, int someOtherArgs) {
this(someOtherArgs, labelAnnotation.getFontSize());
}

public TextAnnotation(int someOtherArgs, int fontSize) {
this.someOtherArgs= someOtherArgs;
this.fontSize = fontSize;
}
}

TextAnnotation 上创建一个构造函数,该构造函数根据 LabelAnnotation 配置构建对象。然后你可以像这样使用它:

TextAnnotation text = new TextAnnotation(someArgs,fontSize);

或使用您的创建者

class TextAnnotationCreator {
TextAnnotation create() {
return
new TextAnnotation(
new LabelAnnotationCreator().create(),
someOtherArgs
);
}
}

关于java - "Creator"配置继承对象的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53411221/

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