Chapter 7 contained a simplified implementation of the builder pattern. In reality engineers often make use of a number of techniques and language features when implementing the builder pattern. Listing C.11, demonstrates a more complete implementation of the builder pattern in Java. Some things to note in this implementation are as follows:
The TextOptions
class constructor is private to force other engineers to use the builder pattern.
The TextOptions
class constructor takes an instance of Builder
as a parameter. This makes the code a little easier to read and maintain because it avoids very long lists of parameters and arguments.
The TextOptions
class provides a toBuilder()
method that can be used to create a prepopulated instance of the Builder
class from an instance of the TextOptions
class.
The Builder
class is an inner class of the TextOptions
class. This serves two purposes:
public final class TextOptions { private final Font font; private final OptionalDouble fontSize; private final Optional<Color> color; private TextOptions(Builder builder) { ❶ font = builder.font; fontSize = builder.fontSize; color = builder.color; } public Font getFont() { return font; } public OptionalDouble getFontSize() { return fontSize; } public Optional<Color> getColor() { return color; } public Builder toBuilder() { ❷ return new Builder(this); } public static final class Builder { ❸ private Font font; private OptionalDouble fontSize = OptionalDouble.empty(); private Optional<Color> color = Optional.empty(); public Builder(Font font) { this.font = font; } private Builder(TextOptions options) { ❹ font = options.font; fontSize = options.fontSize; color = options.color; } public Builder setFont(Font font) { this.font = font; return this; } public Builder setFontSize(double fontSize) { this.fontSize = OptionalDouble.of(fontSize); return this; } public Builder clearFontSize() { fontSize = OptionalDouble.empty(); return this; } public Builder setColor(Color color) { this.color = Optional.of(color); return this; } public Builder clearColor() { color = Optional.empty(); return this; } public TextOptions build() { return new TextOptions(this); } } }
❶ Constructor private and accepts a Builder as a parameter
❷ toBuilder() function allows creation of a pre-populated builder.
❸ The Builder class is an inner class of TextOptions.
❹ Private Builder constructor for copying from some TextOptions
Some examples of how this code might be used are as follows:
TextOptions options1 = new TextOptions.Builder(Font.ARIAL) .setFontSize(12.0) .build(); TextOptions options2 = options1.toBuilder() .setColor(Color.BLUE) .clearFontSize() .build(); TextOptions options3 = options2.toBuilder() .setFont(Font.VERDANA) .setColor(Color.RED) .build();
3.145.115.195