How do I implement the Builder pattern in Java?

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 &amp;, 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.

How do I use java.net.URI with Builder API?

Actually, the standard java.net.URI class in the JDK does not have a built-in Builder API. It only provides constructors and the URI.create(String) factory method.

To build URIs using a builder pattern in Java, you have three common options:

1. Using URI Constructors (Standard JDK)

While not a “builder,” the multi-argument constructor is the safest way to build a URI from components because it automatically handles URL encoding (escaping spaces, special characters, etc.).

import java.net.URI;

URI uri = new URI(
    "https",           // Scheme
    "example.com",     // Host
    "/api/search",     // Path
    "q=java builder",  // Query
    null               // Fragment
);

2. Using UriComponentsBuilder (Spring Framework)

If you are working in a Spring environment, this is the most robust and popular builder API.

import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;

URI uri = UriComponentsBuilder.newInstance()
    .scheme("https")
    .host("example.com")
    .path("/api/users/{id}")
    .queryParam("format", "json")
    .buildAndExpand(123) // Replaces {id} with 123
    .toUri();

3. Using HttpUrl (OkHttp Library)

If you use the OkHttp library, it provides a very clean HttpUrl builder.

import okhttp3.HttpUrl;
import java.net.URI;

URI uri = new HttpUrl.Builder()
    .scheme("https")
    .host("example.com")
    .addPathSegment("search")
    .addQueryParameter("q", "java")
    .build()
    .uri(); // Converts to java.net.URI

4. Why not HttpRequest.newBuilder()?

In your context attachments, you see HttpRequest.newBuilder(). Note that this builds an HTTP Request, not the URI itself. You still need to pass a URI object to the .uri() method:

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://example.com")) // Still requires a URI object
    .GET()
    .build();

Summary: If you want a builder API for java.net.URI without adding external dependencies, your best bet is to create a small helper class or use the multi-argument new URI(...) constructor to ensure proper encoding.