如何使用单个构建器来构建多个对象?
作者:互联网
这个直接来自Effective java 2.我不确定第2项中的这个陈述是什么意思
The Builder pattern is flexible. A single builder can be used to build
multiple objects. The parameters of the builder can be tweaked between
object creations to vary the objects.
我无法想出一个例子来做到这一点.
请举例说明一下.
解决方法:
This博客文章提供了JavaFX 2 API使用的构建器对象的一个很好的示例.
A single builder can be used to build multiple objects.
构建器对象负责构造有效对象,但在调用build()方法之前,不会构造对象.这意味着可以多次使用相同的构建器来构造完全不同的对象.
例:
final TextBuilder builder = TextBuilder.create()
final Text text1 = builder
.text("Hello World!")
.x(50).y(50)
.fill(Color.WHITE)
.font(MY_DEFAULT_FONT)
.build();
final Text text2 = builder
.text("Goodbye World!")
.x(50).y(100)
.fill(Color.WHITE)
.font(MY_DEFAULT_FONT)
.build();
这可以根据您想要创建不同对象的次数来完成.只是为了重新迭代在调用build()方法之前未创建对象的点,请考虑您可以执行以下操作:
final Text text1 = TextBuilder.create()
.text("Hello World!")
.text("Goodbye World!")
.text("Hello There!")
.build();
这将导致创建一个对象,文本设置为“Hello There”,因为这是在调用build()方法之前的属性值.
The parameters of the builder can be tweaked between object creations
to vary the objects.
以下示例演示了这一点.
// Set the properties that are common to all objects.
final TextBuilder builder = TextBuilder.create()
.x(50)
.fill(Color.WHITE)
.font(MY_DEFAULT_FONT);
// Use the builder to construct different objects that have the
// properties set above as well as the additional ones set here.
final Text text1 = builder.text("Hello World!").y(50).build();
final Text text2 = builder.text("Goodbye World!").y(100).build();
final Text text3 = builder.text("JavaFX is fun!").y(150).build();
标签:effective-java,java 来源: https://codeday.me/bug/20190825/1724249.html