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



我有以下对象结构:

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

我想使用"创建者"对象对这些对象进行一些初始化(这种初始化取决于外部设置,所以我不想在这些对象的构造函数中进行。(

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

fontSize = AppDefaults.fontSize

所以我正在写一个"创造者":

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

现在,我想创建一个TextAnnotationCreator。这就是我的困境:我不能使用LabelAnnotationCreator,因为它会创建LabelAnnAnnotation的实例,但另一方面,我希望从LabelAnninationCreator执行的初始化中受益。

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

最新更新