Suppose a reporting application produces a plain text summary for an email and an HTML fragment for a dashboard. Both reports contain a title and a sequence of items. We want to reuse the steps that assemble the report while allowing each output format to control how those steps are represented.
Builder is a Gang of Four creational pattern that separates the construction steps of a complex object from its representation. A director coordinates those steps through a builder interface. Concrete builders assemble the results in their own formats. The GoF describe this intent in their pattern catalog. Design Patterns by Gamma, Helm, Johnson, and Vlissides
This example uses a small report to make the construction sequence visible. The same approach can support richer reports with sections, tables, and summaries.
A complete example
Save the code as BuilderExample.java. It uses only standard Java classes and supports Java 8 or later.
package org.kodejava.pattern.builder;
import java.util.Arrays;
import java.util.List;
public class BuilderExample {
interface ReportBuilder {
void start(String title);
void addItem(String item);
void finish();
String getResult();
}
static final class PlainTextReportBuilder implements ReportBuilder {
private final StringBuilder content = new StringBuilder();
@Override
public void start(String title) {
content.setLength(0);
content.append(title).append("\n");
}
@Override
public void addItem(String item) {
content.append("- ").append(item).append("\n");
}
@Override
public void finish() {
// Plain text needs no closing markup.
}
@Override
public String getResult() {
return content.toString();
}
}
static final class HtmlReportBuilder implements ReportBuilder {
private final StringBuilder content = new StringBuilder();
@Override
public void start(String title) {
content.setLength(0);
content.append("<h1>").append(escape(title)).append("</h1><ul>");
}
@Override
public void addItem(String item) {
content.append("<li>").append(escape(item)).append("</li>");
}
@Override
public void finish() {
content.append("</ul>");
}
@Override
public String getResult() {
return content.toString();
}
private String escape(String value) {
return value.replace("&", "&")
.replace("<", "<")
.replace(">", ">");
}
}
static final class ReportDirector {
void construct(ReportBuilder builder, String title, List<String> items) {
builder.start(title);
for (String item : items) {
builder.addItem(item);
}
builder.finish();
}
}
public static void main(String[] args) {
ReportDirector director = new ReportDirector();
List<String> items = Arrays.asList("Orders: 12", "Returns & exchanges: 2");
ReportBuilder plainText = new PlainTextReportBuilder();
director.construct(plainText, "Weekly report", items);
System.out.print(plainText.getResult());
ReportBuilder html = new HtmlReportBuilder();
director.construct(html, "Weekly report", items);
System.out.println(html.getResult());
}
}
Compile and run it from the directory containing the source.
javac -d out BuilderExample.java
java -cp out org.kodejava.pattern.builder.BuilderExample
The output contains the plain text report followed by the HTML fragment.
Weekly report
- Orders: 12
- Returns & exchanges: 2
<h1>Weekly report</h1><ul><li>Orders: 12</li><li>Returns & exchanges: 2</li></ul>
The HTML builder escapes ampersands and angle brackets in text content. The sample’s ampersand becomes &, keeping it as text inside the list item.
How the construction works
| GoF role | Example | Responsibility |
|---|---|---|
| Builder | ReportBuilder |
Declares the report construction steps. |
| Concrete builders | PlainTextReportBuilder, HtmlReportBuilder |
Assemble the report in each format. |
| Director | ReportDirector |
Calls the steps in the required order. |
| Products | Plain text and HTML strings | Hold the completed representations. |
| Client | main() |
Chooses each builder and retrieves its result. |
The director starts the report, adds each item, then finishes it. It uses the same sequence for both builders. The plain text builder adds line breaks and bullet markers. The HTML builder creates heading and list elements.
Although both results have Java type String, they represent different output formats. Each concrete builder owns the rules for assembling its representation.
The client calls getResult() after construction completes. Calling it earlier would return the content assembled so far. The director supplies the ordering contract for this example.
Each builder’s start() method clears its buffer, so a later construction using that builder replaces the previous report. Previously returned strings retain their contents. The mutable builders should be confined to one construction at a time.
Adding another representation
A new builder can implement the same operations for another report format. The client passes it to the director and retrieves the result after construction. A new construction operation, such as adding a table, requires updating the builder interface, implementations, and director where appropriate.
In Java APIs, you may also encounter fluent builders with chained configuration methods and a final build() call. This example makes the GoF construction process explicit through a director and interchangeable representations. Method chaining is an optional API choice.
When should I use Builder?
Builder fits a construction process with multiple steps that can be reused across different representations. Examples include document generation and assembling complex object structures from parsed input.
The additional interface and classes have a maintenance cost. For a short report with one fixed output format, a single formatting method can be sufficient. As formats and construction rules grow, builders give each representation a dedicated place to manage its assembly.
This continues the creational series after Factory Method and Abstract Factory. The series began with the existing Singleton article. Singleton pattern
Next, we will cover Prototype and create new objects by copying an existing instance.
