📝 What You’ll Learn

  • What the Prototype Pattern is
  • Why and when to use cloning
  • How to implement it in Java
  • Real-world examples and analogies
  • Pitfalls to avoid

🔍 What Is the Prototype Pattern?

The Prototype Pattern lets you create copies of existing objects, avoiding the overhead of creating them from scratch.

Instead of using a constructor, you clone a prototype.

🧪 When to Use It

Use the Prototype Pattern when:

  • Object creation is costly or time-consuming
  • You need many similar objects
  • You want to create copies of objects with slight variations
  • Your system needs to be decoupled from specific classes

🧱 Java Implementation

🧩 Step 1: Make a Cloneable Class

public class Document implements Cloneable {
    private String title;
    private String content;

    public Document(String title, String content) {
        this.title = title;
        this.content = content;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void display() {
        System.out.println("Title: " + title);
        System.out.println("Content: " + content);
    }

    @Override
    public Document clone() {
        try {
            return (Document) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException("Clone not supported!");
        }
    }
}

✅ Usage

Document original = new Document("Original", "This is the content.");
Document copy = original.clone();
copy.setTitle("Copy");

original.display();
copy.display();

🧠 Real-World Analogy

Think of a document template. Instead of writing a new one from scratch every time, you duplicate the original and make small edits. Fast and efficient!

⚠️ Pitfalls to Avoid

  • ❌ Forgetting to implement Cloneable — results in CloneNotSupportedException
  • ❌ Shallow copying when deep cloning is needed (especially with nested objects)
  • ❌ Not handling clone errors properly

✅ Best Practices

  • Prefer overriding clone() with care, or use copy constructors
  • For deep clones, manually clone nested objects
  • Consider serialization for deep cloning if performance isn't critical
  • Use libraries like Apache Commons Lang for easier cloning

📘 Recap

  • Prototype Pattern lets you duplicate objects without knowing their classes
  • Ideal for improving performance when object creation is expensive
  • Java’s Cloneable and clone() provide built-in support
  • Requires caution with deep vs shallow cloning