Prototype Design Pattern in Java
Create new objects by copying a prepared object and customizing the result.
What is Prototype?
Prototype creates a new object by copying an existing object instead of rebuilding every detail. The existing object acts as a prepared template.
Simple report example
A copy method can make the copying rules explicit and safer than an unrestricted clone operation.
public final class Report {
private final String title;
private final List<String> sections;
public Report(String title, List<String> sections) {
this.title = title;
this.sections = new ArrayList<>(sections);
}
public Report copy() {
return new Report(title, sections);
}
}Report monthly = new Report(
"Monthly report", List.of("Summary", "Metrics"));
Report regional = monthly.copy();The copied list is independent from the original list. For nested mutable objects, decide whether a deeper copy is required.
Watch for shallow copies: copying a reference does not copy the object behind it.
Benefits and trade-offs
Benefits
- Reuses expensive setup work.
- Creates similar objects quickly.
- Provides a known baseline for variants.
Trade-offs
- Nested state can be difficult to copy.
- Mutable references can cause surprises.
When should you use it?
- Object creation is expensive.
- Many objects share mostly identical configuration.
- You need independent variations from a template.
Key takeawayPrototype is useful when a prepared template can be copied faster and more safely than rebuilding every detail.
