Java中嵌套生成器模式类
我正在尝试为一个折线图(使用构建器模式)创建一个java类,它包含许多属性。基于这些属性的应用,我尝试创建内部生成器类(例如X轴属性、Y轴属性等)。我是Java新手,我想知道在我的示例中是否可以调用下面这样的生成器对象。我通过一个链接Can the builder pattern ever be doing too much?。这将以增量构建对象。我喜欢这个主意。然而,我不知道如何将其用于我的场景
调用方法:
new LineGraph().UiPropBuilder(ctx)
.setBackgroundColor(Color.BLUE)
.build()
.XAxisProperties()
.enableGridLines(true)
.build()
.YAxisProperties()
.enableGridLines(false)
.build();
可以打电话吗。build()语句只创建一次就可以创建所有对象,而不是重复多次
课程:
public class LineGraph{
private LineGraph()
public static class UiPropBuilder{
private Integer mBackgroundColor;
private Boolean bTouchEnabled;
...
public UiPropBuilder (Context ctx) { this.ctx = ctx; }
public UiPropBuilder setBackgroundColor(Integer mBackgroundColor){ this.mBackgroundColor = mBackgroundColor; return this;}
public UiPropBuilder touchEnabled(Boolean bTouchEnabled){ this.bTouchEnabled = bTouchEnabled; return this;}
... some more properties...
public UiPropBuilder build(){ return new UiPropBuilder(this); }
}
// X-Axis properties builder
public static class XAxisProperties{
// variable declarations and constructor omitted
public XAxisProperties enableGridLines(Boolean enable) {this.enable = enable); return this;}
public XAxisProperties build(){ return new XAxisProperties(this);}
// Y-Axis properties Builder
public static class YAxisProperties{
// variable declarations and constructor omitted
public YAxisProperties enableGridLines(Boolean enable) {this.enable = enable); return this;}
public YAxisProperties build(){ return new YAxisProperties(this);}
}
# 1 楼答案
可以这样做的一种方法是,有3个生成器对象,它们都可以相互引用并在它们之间切换。这与您已经在尝试的操作类似:
一个更复杂的例子是编写类似于step builder工作方式的东西。我们为每个“步骤”定义接口,并在一个类中实现所有这些步骤。“切换”属性的每个方法实际上都返回
this