00:00

Prototype Design Pattern in Java

Last updated:

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

ComponentResponsibilityIn the Enterprise Example
PrototypeInterface that declares the copy operationLoanOffer
Concrete PrototypeImplements the copy for its own class, deciding what to share and what to duplicateHomeLoanOffer, CarLoanOffer
Prototype Registry (optional)Stores ready-made prototypes under keys and returns copiesOfferRegistry
ClientAsks for a copy and customises itThe 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.

Prototype UML class diagram The Client uses OfferRegistry and the LoanOffer interface. OfferRegistry holds many LoanOffer templates. HomeLoanOffer and CarLoanOffer implement LoanOffer, and each copy method returns a new object of its own class. Client uses OfferRegistry - templates: Map<String, LoanOffer> + register(key, offer): void + create(key): LoanOffer * «interface» LoanOffer + copy(): LoanOffer + forCustomer(name): LoanOffer + summary(): String uses implements HomeLoanOffer + copy(): HomeLoanOffer CarLoanOffer + copy(): CarLoanOffer copy() returns a new object of the same concrete class
Prototype: the registry keeps configured templates, and each concrete prototype copies itself through the LoanOffer interface.
  1. LoanOffer is the prototype interface. Its key method is copy().
  2. HomeLoanOffer and CarLoanOffer implement it (dashed line, hollow triangle). Each overrides copy() with a covariant return type, its own class.
  3. OfferRegistry holds many templates (hollow diamond: aggregation, multiplicity *).
  4. The client uses the registry to get a copy, and the LoanOffer interface to work with it. It never names a concrete class.

5. Step-by-Step Execution Flow

  1. At startup, the application builds each template once, doing the expensive work, and registers it.
  2. A request calls registry.create("HOME").
  3. The registry looks up the template and calls template.copy().
  4. HomeLoanOffer.copy() calls its private copy constructor, which copies the rate and creates a new list of documents.
  5. 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 as ArrayList and HashMap override 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:

CampaignWithoutPrototype.java
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);
        }
    }
}
Console
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 CampaignEmail silently 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.

CampaignPrototypeDemo.java
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

Console
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

  1. The template is rendered once.
  2. For each recipient, copy() returns a full duplicate, attachments included.
  3. The template itself still has no recipient.

10. Best Practices and Common Mistakes

Best practices

  • Prefer a copy constructor or copy method to Cloneable in new code: it works with final fields and needs no casts or checked exceptions.
  • Deep-copy every mutable field; share immutable ones such as String, BigDecimal and 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 makes super.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.
  • Cloneable is awkward: a marker interface, a protected method and a checked exception.
  • Every subclass must remember to override the copy.

13. Comparison with Similar Patterns

AspectPrototypeFactory MethodAbstract FactoryBuilder
Creates byCopying an existing objectCalling a subclass's creation methodCalling a family factoryAssembling step by step
Starting pointA configured instanceA classA factory objectAn empty builder
New variantsRegister a new template at runtimeWrite a new subclassWrite a new factoryCall different steps
Main riskShallow-copy bugsMany subclassesMany classesVerbose 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() or clone().
  • 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.