Prototype Design Pattern in Java
The prototype design pattern in Java creates new objects by copying an existing, fully configured object, the prototype, instead of building each one from scratch. The object knows how to copy itself through a method such as copy(), so client code gets a ready-made duplicate without knowing its concrete class or its fields.
It matters when building an object is slow or complicated: rendering an email template, loading interest rates, or assembling a product listing with dozens of settings. Doing that work once and then copying the result is faster and less error-prone than repeating it. Prototype is one of the creational design patterns, and its trickiest part in Java is getting the copy right: shallow or deep.
1. What Is the Prototype Design Pattern?
The GoF intent is: "Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype."
The core idea is to move the knowledge of how to duplicate an object into the object itself. A class exposes a copy operation, and that operation creates a new instance of the same concrete class with the same state. The caller only sees the prototype's interface.
Two kinds of copy matter:
- Shallow copy: fields are copied as they are. Primitive values and references are duplicated, but referenced objects such as lists are shared by the original and the copy.
- Deep copy: mutable referenced objects are copied too, so the copy can change without affecting the original.
Java offers two ways to implement the copy: the built-in Cloneable/clone() mechanism, and a plain copy constructor behind a copy() method. Both appear in the examples.
2. Key Components
| Component | Responsibility | In the Enterprise Example |
|---|---|---|
| Prototype | Interface that declares the copy operation | LoanOffer |
| Concrete Prototype | Implements the copy for its own class, deciding what to share and what to duplicate | HomeLoanOffer, CarLoanOffer |
| Prototype Registry (optional) | Stores ready-made prototypes under keys and returns copies | OfferRegistry |
| Client | Asks for a copy and customises it | The branch-desk tasks in main |
The client asks the registry, or a prototype directly, for a copy. The concrete prototype builds a new instance of itself and returns it through the interface. The client then changes only what differs, such as the customer name.
3. When Is Prototype Useful?
- Expensive setup: a campaign email rendered from a CMS, or a loan offer whose rate comes from a slow rate table.
- Many similar objects: thousands of product listings that share 90% of their settings.
- Unknown concrete classes: code that must duplicate whatever object it was given, such as a "Duplicate" button in an editor.
4. UML Class Diagram
The diagram shows the Enterprise Example.
LoanOffer interface.LoanOfferis the prototype interface. Its key method iscopy().HomeLoanOfferandCarLoanOfferimplement it (dashed line, hollow triangle). Each overridescopy()with a covariant return type, its own class.OfferRegistryholds many templates (hollow diamond: aggregation, multiplicity*).- The client uses the registry to get a copy, and the
LoanOfferinterface to work with it. It never names a concrete class.
5. Step-by-Step Execution Flow
- At startup, the application builds each template once, doing the expensive work, and registers it.
- A request calls
registry.create("HOME"). - The registry looks up the template and calls
template.copy(). HomeLoanOffer.copy()calls its private copy constructor, which copies the rate and creates a new list of documents.- The client calls
forCustomer("Asha")on the copy and reads the summary. The template is never changed.
6. Real-World Use Cases
- E-commerce: "duplicate listing" and product variants that start as a copy of a base product.
- Payments and banking: pre-approved offer templates, or a default transfer request that is copied and filled in per customer.
- Notifications: one rendered campaign message, copied per recipient.
- The JDK:
Object.clone()is the language-level support, and collections such asArrayListandHashMapoverride it. Their documentation states that the copy is shallow: the elements themselves are not cloned. - Spring Framework:
@Scope("prototype")is a different idea despite the name. Spring creates a new bean through its constructor on each request for it; it does not copy an existing instance.
7. Problem Without the Pattern
A campaign sender rebuilds the template per recipient and copies fields by hand:
import java.util.ArrayList;
import java.util.List;
public class CampaignWithoutPrototype {
static final class CampaignEmail {
String subject;
String body;
List<String> attachments = new ArrayList<>();
String recipient;
}
static CampaignEmail renderTemplate() {
System.out.println("Rendering the Diwali template from the CMS..."); // slow call
CampaignEmail email = new CampaignEmail();
email.subject = "Festive sale: 30% off";
email.body = "<html>...</html>";
email.attachments.add("catalogue.pdf");
return email;
}
public static void main(String[] args) {
for (String recipient : List.of("asha@example.com", "ravi@example.com")) {
CampaignEmail template = renderTemplate(); // rebuilt for every recipient
CampaignEmail email = new CampaignEmail(); // client copies field by field
email.subject = template.subject;
email.body = template.body; // attachments forgotten
email.recipient = recipient;
System.out.println(email.recipient + " gets attachments " + email.attachments);
}
}
}
Rendering the Diwali template from the CMS...
asha@example.com gets attachments []
Rendering the Diwali template from the CMS...
ravi@example.com gets attachments []
- Repeated expensive work: the template is rendered once per recipient.
- Fragile copying: the client must know every field, and it forgot
attachments. - Tight coupling: each new field in
CampaignEmailsilently breaks every hand-written copy.
8. Solution Using the Pattern
Render the template once and give CampaignEmail a copy() method. The copying logic now lives next to the fields it copies, so it is written once and updated in one place. The client asks for a copy and sets only the recipient, without seeing the other fields. The Basic Example applies exactly this fix.
9. Prototype Design Pattern in Java: Code Examples
Each example is a single file that runs on Java 21 with java FileName.java.
Basic Example: Campaign Email with a Copy Constructor
Problem: fix section 7, rendering once and copying safely.
import java.util.ArrayList;
import java.util.List;
public class CampaignPrototypeDemo {
// Prototype: anything that can copy itself
interface Prototype<T> {
T copy();
}
static final class CampaignEmail implements Prototype<CampaignEmail> {
private final String subject;
private final String body;
private final List<String> attachments;
private String recipient;
CampaignEmail(String subject, String body, List<String> attachments) {
this.subject = subject;
this.body = body;
this.attachments = new ArrayList<>(attachments);
}
// Copy constructor: the class itself knows every field it must copy
private CampaignEmail(CampaignEmail source) {
this.subject = source.subject;
this.body = source.body;
this.attachments = new ArrayList<>(source.attachments); // own list, not shared
this.recipient = source.recipient;
}
@Override
public CampaignEmail copy() {
return new CampaignEmail(this);
}
CampaignEmail to(String recipient) {
this.recipient = recipient;
return this;
}
@Override
public String toString() {
return recipient + " gets \"" + subject + "\" with " + attachments;
}
}
static CampaignEmail renderTemplate() {
System.out.println("Rendering the Diwali template from the CMS..."); // slow call
return new CampaignEmail("Festive sale: 30% off", "<html>...</html>", List.of("catalogue.pdf"));
}
public static void main(String[] args) {
CampaignEmail template = renderTemplate(); // rendered once
for (String recipient : List.of("asha@example.com", "ravi@example.com")) {
System.out.println(template.copy().to(recipient));
}
System.out.println("Template still has no recipient: " + (template.recipient == null));
}
}
Important classes and methods
Prototype<T>is a small generic interface with one method,copy().- The private copy constructor copies every field and creates a new attachments list.
to()sets the recipient on the copy, never on the template.
Expected output
Rendering the Diwali template from the CMS...
asha@example.com gets "Festive sale: 30% off" with [catalogue.pdf]
ravi@example.com gets "Festive sale: 30% off" with [catalogue.pdf]
Template still has no recipient: true
How it runs
- The template is rendered once.
- For each recipient,
copy()returns a full duplicate, attachments included. - The template itself still has no recipient.
Practical Example: Shallow vs Deep Copy with clone()
Problem: a marketplace lets sellers duplicate a listing to create a refurbished variant. The copy must not change the original's tags.
import java.util.ArrayList;
import java.util.List;
public class ListingCloneDemo {
// Shallow: Object.clone() copies field values, so both objects share one list
static class ShallowListing implements Cloneable {
String title;
List<String> tags = new ArrayList<>();
@Override
public ShallowListing clone() {
try {
return (ShallowListing) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError("Cloneable is implemented", e);
}
}
}
// Deep: clone() also copies the mutable list
static class DeepListing implements Cloneable {
String title;
List<String> tags = new ArrayList<>();
@Override
public DeepListing clone() {
try {
DeepListing copy = (DeepListing) super.clone();
copy.tags = new ArrayList<>(tags); // give the copy its own list
return copy;
} catch (CloneNotSupportedException e) {
throw new AssertionError("Cloneable is implemented", e);
}
}
}
public static void main(String[] args) {
ShallowListing shallowOriginal = new ShallowListing();
shallowOriginal.title = "Noise-cancelling headphones";
shallowOriginal.tags.addAll(List.of("electronics", "audio"));
ShallowListing shallowCopy = shallowOriginal.clone();
shallowCopy.title = "Headphones (refurbished)";
shallowCopy.tags.add("refurbished");
System.out.println("Shallow copy");
System.out.println(" original: " + shallowOriginal.title + " " + shallowOriginal.tags);
System.out.println(" copy: " + shallowCopy.title + " " + shallowCopy.tags);
System.out.println(" same list? " + (shallowOriginal.tags == shallowCopy.tags));
DeepListing deepOriginal = new DeepListing();
deepOriginal.title = "Noise-cancelling headphones";
deepOriginal.tags.addAll(List.of("electronics", "audio"));
DeepListing deepCopy = deepOriginal.clone();
deepCopy.title = "Headphones (refurbished)";
deepCopy.tags.add("refurbished");
System.out.println("Deep copy");
System.out.println(" original: " + deepOriginal.title + " " + deepOriginal.tags);
System.out.println(" copy: " + deepCopy.title + " " + deepCopy.tags);
System.out.println(" same list? " + (deepOriginal.tags == deepCopy.tags));
}
}
Important classes and methods
- Both classes implement
Cloneable. Without it,Object.clone()throwsCloneNotSupportedException. - Each overrides
clone()aspublicwith a covariant return type, so callers need no cast. DeepListing.clone()replaces the copied reference with a new list.
Expected output
Shallow copy
original: Noise-cancelling headphones [electronics, audio, refurbished]
copy: Headphones (refurbished) [electronics, audio, refurbished]
same list? true
Deep copy
original: Noise-cancelling headphones [electronics, audio]
copy: Headphones (refurbished) [electronics, audio, refurbished]
same list? false
How it runs
- The shallow clone gets its own
titlefield but the same list object. - Adding "refurbished" to the copy therefore also changes the original.
- The deep clone has its own list, so the original keeps two tags.
Strings are immutable, so sharing title is safe; only mutable fields need deep copying.
Real-World Enterprise Example: Loan Offer Registry
Problem: a bank's branch desks produce personalised loan offers concurrently. Rates come from a slow rate table, and no customer's offer may change the shared template.
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
public class LoanOfferRegistryDemo {
static final AtomicInteger RATE_TABLE_LOADS = new AtomicInteger(); // counts the expensive step
// Prototype
sealed interface LoanOffer permits HomeLoanOffer, CarLoanOffer {
LoanOffer copy();
LoanOffer forCustomer(String name);
String summary();
}
// Shared state and deep-copy logic for both concrete prototypes
abstract static sealed class BaseOffer permits HomeLoanOffer, CarLoanOffer {
protected final String product;
protected final BigDecimal annualRate;
protected final List<String> requiredDocuments;
protected String customer = "-";
protected BaseOffer(String product, BigDecimal annualRate, List<String> requiredDocuments) {
this.product = product;
this.annualRate = annualRate;
this.requiredDocuments = new ArrayList<>(requiredDocuments);
}
protected BaseOffer(BaseOffer source) { // copy constructor
this(source.product, source.annualRate, source.requiredDocuments); // list is copied again
this.customer = source.customer;
}
public String summary() {
return "%s for %s at %s%% needs %s".formatted(product, customer, annualRate, requiredDocuments);
}
}
// Concrete prototypes
static final class HomeLoanOffer extends BaseOffer implements LoanOffer {
HomeLoanOffer(BigDecimal rate) {
super("Home loan", rate, List.of("PAN", "salary slips", "property papers"));
}
private HomeLoanOffer(HomeLoanOffer source) { super(source); }
@Override
public HomeLoanOffer copy() { return new HomeLoanOffer(this); }
@Override
public HomeLoanOffer forCustomer(String name) {
HomeLoanOffer offer = copy();
offer.customer = name;
return offer;
}
}
static final class CarLoanOffer extends BaseOffer implements LoanOffer {
CarLoanOffer(BigDecimal rate) {
super("Car loan", rate, List.of("PAN", "salary slips", "vehicle quotation"));
}
private CarLoanOffer(CarLoanOffer source) { super(source); }
@Override
public CarLoanOffer copy() { return new CarLoanOffer(this); }
@Override
public CarLoanOffer forCustomer(String name) {
CarLoanOffer offer = copy();
offer.customer = name;
return offer;
}
}
// Prototype registry: templates are built once and only ever copied
static final class OfferRegistry {
private final Map<String, LoanOffer> templates = new ConcurrentHashMap<>();
void register(String key, LoanOffer template) {
templates.put(key, template);
}
LoanOffer create(String key) {
LoanOffer template = Objects.requireNonNull(templates.get(key), () -> "No template for " + key);
return template.copy();
}
}
static BigDecimal loadRateFromRateTable(String product) {
RATE_TABLE_LOADS.incrementAndGet(); // imagine a slow database query here
return product.equals("HOME") ? new BigDecimal("8.40") : new BigDecimal("9.15");
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
OfferRegistry registry = new OfferRegistry();
registry.register("HOME", new HomeLoanOffer(loadRateFromRateTable("HOME")));
registry.register("CAR", new CarLoanOffer(loadRateFromRateTable("CAR")));
List<String> quotes = new ArrayList<>();
List<String> requests = List.of("HOME:Asha", "CAR:Ravi", "HOME:Meera", "CAR:Kabir");
try (ExecutorService branchDesks = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<String>> futures = new ArrayList<>();
for (String request : requests) {
String[] parts = request.split(":");
futures.add(branchDesks.submit(() -> registry.create(parts[0]).forCustomer(parts[1]).summary()));
}
for (Future<String> future : futures) {
quotes.add(future.get()); // results kept in request order
}
}
quotes.forEach(System.out::println);
System.out.println("Rate table loads: " + RATE_TABLE_LOADS.get());
System.out.println("Template untouched: " + registry.create("HOME").summary());
}
}
Important classes and methods
LoanOfferis a sealed prototype interface;BaseOfferholds the shared copy constructor.OfferRegistryis a prototype registry. Itscreate()never returns a template, only a copy.forCustomer()also works on a copy, so even a direct call cannot change a template.- Tasks run on virtual threads. They are safe because templates are only read, never written.
Expected output
Home loan for Asha at 8.40% needs [PAN, salary slips, property papers]
Car loan for Ravi at 9.15% needs [PAN, salary slips, vehicle quotation]
Home loan for Meera at 8.40% needs [PAN, salary slips, property papers]
Car loan for Kabir at 9.15% needs [PAN, salary slips, vehicle quotation]
Rate table loads: 2
Template untouched: Home loan for - at 8.40% needs [PAN, salary slips, property papers]
How it runs
- Two templates are built, so the rate table is read twice in total.
- Four requests copy a template in parallel and personalise the copy.
- Results are collected in request order through the futures.
- A final copy shows the template still has no customer.
10. Best Practices and Common Mistakes
Best practices
- Prefer a copy constructor or copy method to
Cloneablein new code: it works withfinalfields and needs no casts or checked exceptions. - Deep-copy every mutable field; share immutable ones such as
String,BigDecimaland records of immutable values. - Never hand out the template itself; return copies from the registry.
- Thread safety: copying a template that nobody modifies is safe from many threads. To change a template, build a new one and replace the map entry.
Common mistakes
- Accidental shallow copies that share lists, maps or arrays.
- Forgetting
Cloneable, which makessuper.clone()throw. - Copying through serialization for convenience: slow and fragile.
- Overengineering: adding
copy()to cheap objects that a constructor or builder creates just as easily.
11. When to Use and When Not to Use
Use it when the configured state is the valuable part, when callers must duplicate objects whose class they do not know, or when a registry of templates replaces a pile of subclasses.
Avoid it for immutable objects, which can simply be shared, for objects holding resources such as sockets or open files, which should not be duplicated, and for deep object graphs with cycles, where a correct copy becomes complicated.
12. Advantages and Disadvantages
Advantages
- Expensive setup runs once.
- Copy logic lives with the data, so it stays correct as fields change.
- Clients stay decoupled from concrete classes.
- New variants at runtime by registering new templates instead of writing subclasses.
Disadvantages
- Deep copies are easy to get wrong, especially with nested or cyclic objects.
Cloneableis awkward: a marker interface, a protected method and a checked exception.- Every subclass must remember to override the copy.
13. Comparison with Similar Patterns
| Aspect | Prototype | Factory Method | Abstract Factory | Builder |
|---|---|---|---|---|
| Creates by | Copying an existing object | Calling a subclass's creation method | Calling a family factory | Assembling step by step |
| Starting point | A configured instance | A class | A factory object | An empty builder |
| New variants | Register a new template at runtime | Write a new subclass | Write a new factory | Call different steps |
| Main risk | Shallow-copy bugs | Many subclasses | Many classes | Verbose setup code |
Choose Prototype when an existing object already holds the state you want. Choose Builder when objects are assembled from many independent options, and a factory when the class to create is what varies. They combine well: an Abstract Factory can store prototypes and return copies, and a builder can start from a copy of a template.
14. Summary
- The prototype design pattern in Java creates objects by copying a configured prototype.
- Purpose: avoid repeating expensive setup and keep copy logic inside the class.
- Components: Prototype interface, Concrete Prototypes, optional Registry, Client.
- Each concrete prototype returns a new object of its own class from
copy()orclone(). - Used for templates, offers, product variants and "duplicate" features.
- Benefits: speed, consistency and decoupled clients.
- Deep-copy mutable fields, prefer copy constructors, and never hand out the template itself.
15. Java Design Pattern Interview Questions and Answers
Q1. Why do many developers consider Cloneable broken?
Cloneable is a marker interface with no clone() method, so it does not make the method callable; Object.clone() is protected and throws a checked exception. clone() creates the object without running a constructor, and it cannot assign final fields, which blocks deep copies of final mutable fields. Effective Java therefore recommends copy constructors or copy factories instead.
Q2. Is Spring's prototype scope an implementation of the Prototype pattern?
No. With @Scope("prototype"), the container creates a brand-new bean by calling its constructor and running injection each time the bean is requested. Nothing is copied from an existing instance. The two share a name only because both produce a new object per request.
Q3. How would you deep-copy an object graph that contains cycles?
Keep a map from original objects to their copies, keyed by identity, and check it before copying any object. When an object has already been copied, reuse that copy instead of recursing, which ends the cycle and keeps shared references shared.
Node deepCopy(Node node, Map<Node, Node> copies) { // pass new IdentityHashMap<>()
Node existing = copies.get(node);
if (existing != null) return existing;
Node copy = new Node(node.name());
copies.put(node, copy); // register before visiting neighbours
for (Node next : node.links()) copy.link(deepCopy(next, copies));
return copy;
}Q4. Do immutable objects need a copy method?
No. An immutable object, such as a record whose components are all immutable, can be shared safely, so its "copy" can simply be the same reference. To change one value, Java code uses "with" methods that return a new instance, for example offer.withRate(newRate). Prototype pays off for mutable objects.
Q5. Operations want to update a template's rate while requests are copying it. How do you keep that safe?
Do not modify the template in place: a copy taken halfway through an update could see mixed values. Build a new template with the new rate and replace the registry entry with templates.put(key, newTemplate) on the ConcurrentHashMap. Each request then copies either the old or the new template, never a mixture.