How do I implement the Prototype pattern in Java?

Suppose an application creates monthly sales reports with the same initial sections. A configured report can serve as a template. Each month, the application copies it, changes the title, and adds the sections needed for that month.

Prototype is a Gang of Four creational pattern that creates objects by copying an existing instance. The prototype carries the configuration from which new objects are produced. A client can request a copy through an interface while the concrete class implements its copying rules. GoF pattern catalog

This article completes our creational patterns series following Factory Method, Abstract Factory, and Builder. The series began with the existing Singleton example. Singleton pattern

A complete example

Save the following code as PrototypeExample.java. It uses standard Java APIs available in Java 8 and later.

package org.kodejava.pattern.prototype;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class PrototypeExample {
    interface Report {
        Report copy();
        void setTitle(String title);
        void addSection(String section);
    }

    static final class SalesReport implements Report {
        private String title;
        private final List<String> sections;

        SalesReport(String title, List<String> sections) {
            this.title = Objects.requireNonNull(title);
            this.sections = new ArrayList<>(sections);
        }

        private SalesReport(SalesReport original) {
            this(original.title, original.sections);
        }

        @Override
        public SalesReport copy() {
            return new SalesReport(this);
        }

        @Override
        public void setTitle(String title) {
            this.title = Objects.requireNonNull(title);
        }

        @Override
        public void addSection(String section) {
            sections.add(Objects.requireNonNull(section));
        }

        @Override
        public String toString() {
            return title + " " + sections;
        }
    }

    static Report customize(Report prototype) {
        Report report = prototype.copy();
        report.setTitle("November sales");
        report.addSection("Regional totals");
        return report;
    }

    public static void main(String[] args) {
        Report template = new SalesReport("Sales template",
                Arrays.asList("Summary", "Revenue"));
        Report november = customize(template);

        System.out.println("Template: " + template);
        System.out.println("Copy: " + november);
        System.out.println("Same instance: " + (template == november));

        november.addSection("Forecast");
        System.out.println("Template after edit: " + template);
        System.out.println("Copy after edit: " + november);
    }
}

Compile and run the example from the directory containing the source file.

javac -d out PrototypeExample.java
java -cp out org.kodejava.pattern.prototype.PrototypeExample

The program prints the original template and customized copy, then edits the copy again.

Template: Sales template [Summary, Revenue]
Copy: November sales [Summary, Revenue, Regional totals]
Same instance: false
Template after edit: Sales template [Summary, Revenue]
Copy after edit: November sales [Summary, Revenue, Regional totals, Forecast]

How copying works

GoF role Example Responsibility
Prototype Report Declares the copying operation used by the client.
Concrete prototype SalesReport Copies its title and sections according to its own rules.
Client customize() Obtains a copy through the interface and customizes it.
Configured prototype instance template in main() Supplies the initial report state.

The application creates the template once. The customize() method receives it through the Report interface and calls copy(). The concrete prototype returns a new SalesReport using a private copy constructor. Another report implementation could supply its own copying behavior through the same interface.

The false identity comparison shows that the template and copy are distinct report instances. Their section lists are also separate. The constructor creates a new ArrayList, so adding Regional totals or Forecast to the copy leaves the template’s sections intact.

The list elements are strings, which are immutable, so both lists can safely refer to the same section strings. If sections become mutable objects with their own fields, copying the list will still share those elements. The copy implementation must then decide which elements to duplicate and which references to share.

Choosing a copy policy

A useful copy contract states what the new object inherits and what becomes independent. In this example, the copy starts with the same title and section values, then owns its own mutable section list. A business object might also need a new identifier or a cleared creation timestamp.

Java provides Object.clone(), whose default behavior copies field values and shares referenced objects. This is a shallow copy. Our example exposes an explicit copy() method and constructs its result with the required list ownership. The Prototype pattern’s copying contract can be implemented this way. Object.clone() documentation

More elaborate object graphs require additional decisions. Shared subobjects, cycles, open resources, and external identities all affect what a valid copy means. Keep those decisions in the concrete prototype and document them for callers.

When should I use Prototype?

Prototype fits applications that repeatedly create objects from configured templates, particularly when client code works with multiple concrete types through a shared interface. A registry of named templates can let callers choose the starting configuration at runtime.

Copying also has a maintenance cost. When fields are added, review the copy operation so the new state receives the intended treatment. Copying large mutable graphs can consume substantial memory and time. Measure the actual construction and copying costs before choosing Prototype for performance.

For a small object with straightforward initialization, a constructor or factory can be sufficient. Prototype becomes useful when an existing instance provides the state needed to create another object.

Next, we begin structural patterns with Adapter.

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.