GoF pattern • Creational
GoFCreationalJava example
Prototype solves a specific structural problem in the design.
Create new objects by copying an existing configured instance.
Pattern overview
GoF pattern
Create new objects by copying an existing configured instance.
Intent
Specify kinds of objects to create using a prototypical instance, then create copies from it.
Problem
Object setup is expensive or repetitive, but new instances should start from a known template.
Solution
Store a configured prototype and clone or copy it when a new instance is needed.
Fit and tradeoffs
FamilyGoF
CategoryCreational
Best used when
- When object creation cost is high or setup is repetitive.
- When many variants share a common baseline configuration.
Tradeoffs
- Cloning semantics can become subtle with nested mutable state.
- Copying can hide how new objects are really initialized.
Java example
This example is intentionally compact so the pattern shape stays easy to see.
public final class EmailTemplate {
private final String subject;
private final String body;
public EmailTemplate(String subject, String body) {
this.subject = subject;
this.body = body;
}
public EmailTemplate copyWithSubject(String newSubject) {
return new EmailTemplate(newSubject, body);
}
}