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 implement the Abstract Factory pattern in Java?

A report exporter that supports CSV and TSV needs to make two decisions together. A CSV file should have comma-separated rows and a .csv extension. A TSV file should have tab-separated rows and a .tsv extension. If the exporter chooses these independently, it can give a tab-separated file a CSV name.

Abstract Factory is a Gang of Four creational pattern that groups the creation of related products behind a shared interface. In this example, the application chooses an export factory once and uses it to obtain a matching row formatter and file naming policy. Design Patterns: Abstract Factory

This article follows Factory Method in the creational patterns series, which began with Singleton.

A complete example

Save the following as AbstractFactoryExample.java. The example previews one row with two integer fields, so it can focus on how the factory selects the delimiter and file extension.

package org.kodejava.pattern.abstractfactory;

public class AbstractFactoryExample {
    interface RowFormatter {
        String format(int orderId, int quantity);
    }

    interface FileNaming {
        String fileName(String baseName);
    }

    interface ExportFactory {
        RowFormatter createRowFormatter();
        FileNaming createFileNaming();
    }

    static final class CsvRowFormatter implements RowFormatter {
        @Override
        public String format(int orderId, int quantity) {
            return orderId + "," + quantity;
        }
    }

    static final class CsvFileNaming implements FileNaming {
        @Override
        public String fileName(String baseName) {
            return baseName + ".csv";
        }
    }

    static final class CsvExportFactory implements ExportFactory {
        @Override
        public RowFormatter createRowFormatter() {
            return new CsvRowFormatter();
        }

        @Override
        public FileNaming createFileNaming() {
            return new CsvFileNaming();
        }
    }

    static final class TsvRowFormatter implements RowFormatter {
        @Override
        public String format(int orderId, int quantity) {
            return orderId + "\t" + quantity;
        }
    }

    static final class TsvFileNaming implements FileNaming {
        @Override
        public String fileName(String baseName) {
            return baseName + ".tsv";
        }
    }

    static final class TsvExportFactory implements ExportFactory {
        @Override
        public RowFormatter createRowFormatter() {
            return new TsvRowFormatter();
        }

        @Override
        public FileNaming createFileNaming() {
            return new TsvFileNaming();
        }
    }

    static void previewExport(ExportFactory factory) {
        RowFormatter formatter = factory.createRowFormatter();
        FileNaming naming = factory.createFileNaming();

        System.out.println(naming.fileName("orders"));
        System.out.println(formatter.format(1042, 3));
    }

    public static void main(String[] args) {
        previewExport(new CsvExportFactory());
        previewExport(new TsvExportFactory());
    }
}

Compile and run the example.

javac -d out AbstractFactoryExample.java
java -cp out org.kodejava.pattern.abstractfactory.AbstractFactoryExample

The first row uses a comma. The second uses a tab.

orders.csv
1042,3
orders.tsv
1042    3

How the products stay in sync

GoF role Java example Responsibility
Abstract factory ExportFactory Declares an operation for each product type.
Concrete factories CsvExportFactory, TsvExportFactory Supply the products for one export format.
Abstract products RowFormatter, FileNaming Define the operations the client uses.
Concrete products CsvRowFormatter, CsvFileNaming, TsvRowFormatter, TsvFileNaming Implement the delimiter and extension for their format.
Client previewExport() Uses both products from the factory it receives.

Follow the CSV call from main(). The client receives a CsvExportFactory through the ExportFactory interface. It asks the factory for both products, then calls them through their respective interfaces. The TSV call runs the same client code with a different factory. The matching pair comes from using the same factory for both requests. A factory implementation still has to honor that contract.

The previous article used Factory Method to let a subclass choose the product used by a shared notification workflow. Here, the exporter receives a factory object that supplies two related product types. The GoF describe factory methods as one way to implement the creation operations of an Abstract Factory. Design Patterns: Abstract Factory

When should I use it?

Use Abstract Factory when several components vary together and the client needs to switch among complete families. For example, a real exporter might pair a row formatter with a format-specific escaping policy and media type.

Adding a pipe-delimited family requires a new factory and its products. The previewExport() method can already use that factory through ExportFactory. Adding a new product type, such as a separate header formatter, means adding a creation method to ExportFactory and implementing it for every format. This structure fits applications where the set of product types is fairly stable.

For an exporter whose only differences are a delimiter and a file extension, one configuration object can hold both values. Separate product interfaces earn their place when each format supplies behavior that varies independently of those settings.

The next article covers Builder.

How do I implement the Factory Method pattern in Java?

The Factory Method pattern is a Gang of Four (GoF) creational design pattern. It defines an operation for creating a product while allowing subclasses to choose the concrete product returned. This lets a base class reuse a workflow without hard-coding the product implementation into that workflow.

This article continues our creational patterns series after Singleton. Here, we focus on choosing an implementation through subclassing.

The problem

Suppose an application sends notifications by email and SMS. Both channels support the same operation, send(), but each has its own implementation.

We want a notification service to follow a shared workflow: create a notification, then send the message. The shared workflow should work with either channel. Factory Method gives subclasses a creation step to customize.

A complete example

Save the following code as FactoryMethodExample.java. The classes are nested so that the entire example fits into one source file. In a larger application, you can place them in separate files.

package org.kodejava.pattern.factorymethod;

public class FactoryMethodExample {
    interface Notification {
        void send(String message);
    }

    static class EmailNotification implements Notification {
        @Override
        public void send(String message) {
            System.out.println("Email: " + message);
        }
    }

    static class SmsNotification implements Notification {
        @Override
        public void send(String message) {
            System.out.println("SMS: " + message);
        }
    }

    abstract static class NotificationService {
        protected abstract Notification createNotification();

        public void notifyUser(String message) {
            Notification notification = createNotification();
            notification.send(message);
        }
    }

    static class EmailNotificationService extends NotificationService {
        @Override
        protected Notification createNotification() {
            return new EmailNotification();
        }
    }

    static class SmsNotificationService extends NotificationService {
        @Override
        protected Notification createNotification() {
            return new SmsNotification();
        }
    }

    public static void main(String[] args) {
        NotificationService email = new EmailNotificationService();
        email.notifyUser("Your order has been shipped.");

        NotificationService sms = new SmsNotificationService();
        sms.notifyUser("Your verification code is 482731.");
    }
}

The channel implementations print messages to the console to keep the example self-contained. They do not contact an email provider or SMS gateway.

Compile and run from the directory containing the source file:

javac -d out FactoryMethodExample.java
java -cp out org.kodejava.pattern.factorymethod.FactoryMethodExample

Output:

Email: Your order has been shipped.
SMS: Your verification code is 482731.

How it works

The example has four roles:

GoF role Example Responsibility
Product Notification Declares the operation shared by all notifications.
Concrete products EmailNotification, SmsNotification Implement the channel behavior.
Creator NotificationService Declares the factory method and uses its result in a shared workflow.
Concrete creators EmailNotificationService, SmsNotificationService Override the factory method to choose a concrete product.

The factory method is createNotification(). The inherited notifyUser() method calls it and uses the returned Notification without needing to know its concrete class.

Java supports this structure through abstract methods and method overriding: each concrete service supplies the creation behavior declared by its abstract superclass. See Java’s documentation on abstract methods and classes.

The client still selects a concrete service in main(). The pattern moves product creation behind an overridable method; it does not eliminate the need to choose which service the application uses.

Adding another channel

To support push notifications, implement Notification in a new PushNotification class. Then extend NotificationService and override createNotification() to return that product. The existing notifyUser() workflow can remain unchanged.

This example creates a new product for each call. Factory Method itself does not require a new instance every time; an implementation can return a reusable product if its lifecycle and thread-safety requirements allow it.

Factory Method versus a simple factory

A utility such as NotificationFactory.create("email"), with a conditional selecting a concrete class, is commonly called a simple factory. That can be useful, but it does not demonstrate the subclass-based creation mechanism shown here.

In this example, the defining relationship is that the creator’s shared workflow invokes a factory method overridden by its subclasses. Merely naming a method create() does not establish that structure.

When should I use it?

Use Factory Method when a base class has useful shared behavior, but subclasses need to customize the products that behavior uses. It is especially suitable for extension points in frameworks or reusable libraries.

The tradeoff is additional classes and inheritance. If all you need is a small conditional that constructs an object, a simple factory may be sufficient. If callers can supply an already-created Notification, constructor injection may provide a simpler way to customize the behavior.

Next in this series: Abstract Factory, which focuses on creating families of related products.

How do I implement a Singleton pattern?

Singleton Pattern is used when we want to allow only a single instance of a class can be created inside our application. This pattern ensures that a class only have a single instance by protecting the class creation process, which can be done by defining the class constructor with private access modifier.

To get an instance of a singleton we provide a getInstance() method, this will be the only method that can be accessed to get an instance of the singleton class.

package org.kodejava.pattern.factory;

public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {
    }

    public static synchronized Singleton getInstance() {
        return instance;
    }

    public void doSomething() {
        for (int i = 0; i < 10; i++) {
            System.out.println("i = " + i);
        }
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Clone is not allowed.");
    }
}

There are some rules that need to be followed when we want to implement a singleton.

  • From code above we can see that a singleton has a static variable to keep it sole instance.
  • We need to set the class constructor into private access modifier. By this we will not allow any other class to create an instance of this singleton because they have no access to the constructor.
  • Because no other class can instantiate this singleton how can we use it? the answer is the singleton should provide a service to it users by providing some method that returns the instance, for example getInstance().
  • When we use our singleton in a multi threaded application we need to make sure that instance creation process not resulting more that one instance, so we add a synchronized keywords to protect more than one thread access this method at the same time.
  • It is also advisable to override the clone() method of the java.lang.Object class and throw CloneNotSupportedException so that another instance cannot be created by cloning the singleton object.

And this is how we use the singleton class.

package org.kodejava.pattern.factory;

public class SingletonDemo {
    public static void main(String[] args) {
        // Gets an instance of Singleton class and calls the
        // doSomething method.
        Singleton singleton = Singleton.getInstance();
        singleton.doSomething();
    }
}