gpt4 book ai didi

java - 如何使用单个构建器构建多个对象?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:50:13 26 4
gpt4 key购买 nike

这个直接来自 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.

builder 对象负责构造一个有效的对象,但是 直到您调用 build() 方法才会构造该对象。这意味着可以使用相同的 builder多次构建完全不同的对象。

示例:

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

关于java - 如何使用单个构建器构建多个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14429043/

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