This blog post provides a good example of builder objects being used by the JavaFX 2 API.
A single builder can be used to build multiple objects.
The builder object is responsible for constructing a valid object but The object is not constructed until you call the build()
method. This means the same builder can be used multiple times to construct completely different objects.
Example:
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();
This can be done as many times as you want to create different objects. Just to re-iterate the point that the object is not created until the build()
method is called, consider that you could do the following:
final Text text1 = TextBuilder.create()
.text("Hello World!")
.text("Goodbye World!")
.text("Hello There!")
.build();
which would result in the creation of one object, with the text set to 'Hello There' as this is the value of the property prior to the build()
method being called.
The parameters of the builder can be tweaked between object creations to vary the objects.
The example below demonstrates this.
// 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();