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.