Creational Design Pattern

Prototype Design Pattern in Java

Create new objects by copying an existing configured object instead of rebuilding it from scratch.

In this lesson: The Prototype pattern creates an object by copying a prototype instance. It is useful when object creation is expensive, configuration is complex, or many objects share a common starting state.

Overview

A prototype should define how it is copied. A shallow copy duplicates the top-level object but may share nested references, while a deep copy also duplicates the mutable objects inside it.

Implementation

public interface Prototype<T> {
    T copy();
}

public final class Report implements Prototype<Report> {
    private final String title;
    private final List<String> sections;

    public Report(String title, List<String> sections) {
        this.title = title;
        this.sections = sections;
    }

    public Report copy() {
        return new Report(title, new ArrayList<>(sections));
    }
}

The client can now create a fresh object from an existing prototype while the copy logic remains inside the prototype type.

Report template = new Report(
    "Monthly Sales",
    List.of("Summary", "Revenue", "Products")
);

Report report = template.copy();

Example usage

Use Prototype when a configured object is easier to copy than to construct. Be careful with mutable nested fields, resource handles, database connections, and other values that should not be duplicated directly.

When should you use it?

Use Prototype when a configured object is easier to copy than to construct. Be careful with mutable nested fields and resources that should not be duplicated.

Next step: Continue with the Design Patterns course and explore the next pattern category.