“创建者”模式来配置继承的对象

时间:2018-11-21 11:35:19

标签: java design-patterns prototype factory builder

我具有以下对象结构:

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,因为它会创建LabelAnnotation的实例,但另一方面,我想从LabelAnnotationCreator执行的初始化中受益。

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

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

谢谢!

1 个答案:

答案 0 :(得分:0)

您对此有何看法:

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
           );
    }
} 
相关问题