Advanced Java September 20 ,2025

Prototype Design Pattern in Java

Introduction

The Prototype Pattern is a creational design pattern that enables creating new objects by cloning existing ones rather than creating them from scratch. This is especially useful when object creation is costly, complex, or resource-intensive.

The main idea is:

  • Instead of instantiating a new object every time, you copy an existing object and modify it as needed.
  • This pattern leverages the Cloneable interface in Java or custom cloning logic.

Real-world analogy:

  • Imagine a document template: instead of creating a new document with the same formatting every time, you make a copy of the template and edit it.
  • Similarly, in software, you can clone objects to save setup time and maintain consistency.

Problem Statement

Consider an object that requires expensive initialization, such as loading configuration from a database or performing complex calculations:

class HeavyObject {
    private String data;

    public HeavyObject() {
        // Simulate resource-intensive initialization
        System.out.println("Loading heavy object...");
        this.data = "Important Data";
    }

    public void showData() {
        System.out.println(data);
    }
}

// Usage
HeavyObject obj1 = new HeavyObject(); // Initialization is costly
HeavyObject obj2 = new HeavyObject(); // Expensive again

Problems:

  1. Performance overhead due to repeated initialization.
  2. Duplicate code if each object is manually configured.
  3. Memory usage if many identical objects are created.

The Prototype Pattern solves this by cloning an existing object instead of creating new ones from scratch.

Implementation in Java

Step 1: Define a Prototype Interface

public interface Prototype extends Cloneable {
    Prototype clone();
}
  • The Prototype interface declares a clone() method.
  • All objects that need to be cloned will implement this interface.

Step 2: Implement the Prototype

public class Document implements Prototype {
    private String content;
    private String author;

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

    public void showDocument() {
        System.out.println("Document Content: " + content + ", Author: " + author);
    }

    @Override
    public Prototype clone() {
        return new Document(this.content, this.author);
    }

    // Setters for modification after cloning
    public void setContent(String content) {
        this.content = content;
    }

    public void setAuthor(String author) {
        this.author = author;
    }
}

Step 3: Using the Prototype

public class Main {
    public static void main(String[] args) {
        // Create original object
        Document original = new Document("Design Patterns in Java", "Saumya");
        original.showDocument();

        // Clone the original object
        Document copy1 = (Document) original.clone();
        copy1.setContent("Advanced Java Patterns");
        copy1.setAuthor("John");

        Document copy2 = (Document) original.clone();
        copy2.setContent("Java Best Practices");
        copy2.setAuthor("Alice");

        // Display all documents
        original.showDocument();
        copy1.showDocument();
        copy2.showDocument();
    }
}

Output:

Document Content: Design Patterns in Java, Author: Saumya
Document Content: Advanced Java Patterns, Author: John
Document Content: Java Best Practices, Author: Alice

Explanation:

  • original.clone() creates new objects efficiently without re-running heavy initialization.
  • Each clone can be modified independently while sharing the same initial state.

Deep Cloning vs Shallow Cloning

  1. Shallow Cloning:
    • Copies the object reference but not the objects it refers to.
    • Changes in the referenced objects affect all clones.
@Override
public Prototype clone() {
    try {
        return (Prototype) super.clone(); // shallow copy
    } catch (CloneNotSupportedException e) {
        return null;
    }
}
  1. Deep Cloning:
    • Creates a complete copy of the object and all objects it references.
    • Changes in one clone do not affect others.
@Override
public Prototype clone() {
    return new Document(new String(this.content), new String(this.author)); // deep copy
}

Rule of Thumb: Use deep cloning if objects contain mutable references.

More detail- Deep Cloning vs Shallow Cloning

Real-World Analogies

  • Document Templates: Clone a template instead of creating a new document with the same formatting.
  • Graphic Editor: Copy shapes, images, or objects instead of creating them from scratch.
  • Game Development: Clone enemies, weapons, or NPCs with default properties and then customize them.

Advantages of Prototype Pattern

  1. Performance Improvement:
    • Avoids expensive object creation processes.
    • Useful for objects that are costly to instantiate.
  2. Reduced Code Duplication:
    • No need to write repetitive initialization code.
  3. Flexibility:
    • Clones can be customized after creation without affecting the original.
  4. Dynamic Object Creation:
    • Objects can be created at runtime based on existing prototypes.

Disadvantages

  1. Complexity:
    • Implementing deep cloning can be tricky, especially for objects with nested references.
  2. Maintenance Overhead:
    • If the prototype class changes, all cloning logic must be updated.
  3. Hidden Object Graph Issues:
    • Shallow copies can unintentionally share mutable objects.

When to Use

  • When creating a new object is expensive or resource-intensive.
  • When you want to avoid subclassing for object creation.
  • When you need dynamic runtime object creation.
  • When you want to decouple your code from specific classes, relying on cloning instead.

Conclusion

The Prototype Pattern is a powerful creational pattern for efficient, flexible object creation. By cloning existing objects, you save initialization time, reduce code duplication, and maintain consistency.

  • It’s particularly useful for document templates, game objects, or resource-heavy objects.
  • Choosing between shallow and deep cloning is critical to avoid shared mutable state issues.
  • Prototype is often used in combination with Factory patterns to dynamically create objects at runtime.

Next, we can move to the Builder Design Pattern, which allows constructing complex objects step by step without exposing complicated constructors, ideal for objects with many optional parameters.

 

Sanjiv
0

You must logged in to post comments.

Get In Touch

G06, Kristal Olivine Bellandur near Bangalore Central Mall, Bangalore Karnataka, 560103

+91-8076082435

techiefreak87@gmail.com