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.

Related Blogs

Generics P...
Advanced Java August 08 ,2025

Generics Part- 2

Collection...
Advanced Java July 07 ,2025

Collections Framewor...

Mastering...
Advanced Java August 08 ,2025

Mastering Java Multi...

Annotation...
Advanced Java August 08 ,2025

Annotations

Java Multi...
Advanced Java August 08 ,2025

Java Multithreading...

Java Memor...
Advanced Java August 08 ,2025

Java Memory Manageme...

Java Lambd...
Advanced Java August 08 ,2025

Java Lambda Expressi...

Java Funct...
Advanced Java August 08 ,2025

Java Functional Inte...

Java Strea...
Advanced Java August 08 ,2025

Java Stream API

JDBC (Java...
Advanced Java August 08 ,2025

JDBC (Java Database...

JDBC (Java...
Advanced Java September 09 ,2025

JDBC (Java Database...

Annotation...
Advanced Java August 08 ,2025

Annotations

Generics
Advanced Java August 08 ,2025

Generics

Java I/O (...
Advanced Java August 08 ,2025

Java I/O (NIO)

Introducti...
Advanced Java September 09 ,2025

Introduction to Desi...

Design Pat...
Advanced Java September 09 ,2025

Design Patterns in J...

Other Prin...
Advanced Java September 09 ,2025

Other Principles Beh...

Creational...
Advanced Java September 09 ,2025

Creational Design Pa...

In Creatio...
Advanced Java September 09 ,2025

In Creational Design...

In Creatio...
Advanced Java September 09 ,2025

In Creational Design...

Creational...
Advanced Java September 09 ,2025

Creational Design Pa...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Builder De...
Advanced Java September 09 ,2025

Builder Design Patte...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Structural...
Advanced Java September 09 ,2025

Structural Design Pa...

Design Pat...
Advanced Java September 09 ,2025

Design Patterns in J...

Chain of R...
Advanced Java September 09 ,2025

Chain of Responsibil...

Command De...
Advanced Java September 09 ,2025

Command Design Patte...

Interprete...
Advanced Java September 09 ,2025

Interpreter Design P...

Iterator D...
Advanced Java September 09 ,2025

Iterator Design Patt...

Mediator D...
Advanced Java September 09 ,2025

Mediator Design Patt...

Memento De...
Advanced Java September 09 ,2025

Memento Design Patte...

Observer D...
Advanced Java September 09 ,2025

Observer Design Patt...

State Desi...
Advanced Java September 09 ,2025

State Design Pattern...

Strategy D...
Advanced Java September 09 ,2025

Strategy Design Patt...

Template M...
Advanced Java September 09 ,2025

Template Method Desi...

Visitor De...
Advanced Java September 09 ,2025

Visitor Design Patte...

Prototype...
Advanced Java September 09 ,2025

Prototype Design Pat...

Java 8+ Fe...
Advanced Java October 10 ,2025

Java 8+ Features

SOLID Prin...
Advanced Java October 10 ,2025

SOLID Principles in...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

How Iterat...
Advanced Java October 10 ,2025

How Iterators Work i...

How Concur...
Advanced Java October 10 ,2025

How ConcurrentHashMa...

Comparable...
Advanced Java October 10 ,2025

Comparable vs Compar...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

Semaphore...
Advanced Java October 10 ,2025

Semaphore in Java

ExecutorSe...
Advanced Java October 10 ,2025

ExecutorService in J...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

Producer-C...
Advanced Java October 10 ,2025

Producer-Consumer Pr...

Implementi...
Advanced Java October 10 ,2025

Implementing a Custo...

Busy Spin
Advanced Java October 10 ,2025

Busy Spin

Serializat...
Advanced Java October 10 ,2025

Serialization and De...

Segment Lo...
Advanced Java October 10 ,2025

Segment Locking in J...

Tree Bins...
Advanced Java October 10 ,2025

Tree Bins in Java

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

Custom Imp...
Advanced Java October 10 ,2025

Custom Implementatio...

Get In Touch

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

+91-8076082435

techiefreak87@gmail.com