Prototype Design Pattern in Java
Learn Prototype Design Pattern in Java with cloning, shallow copy, deep copy, diagrams, real-world examples, framework usage, code examples, benefits, limitations, and interview questions.
Introduction
Imagine creating an object is expensive.
Examples:
- Loading a large configuration
- Reading millions of records
- Creating a complex report
- Loading product catalogs
- Creating large object graphs
Creating the object repeatedly wastes time and resources.
Instead of creating a new object from scratch, we can copy an existing object.
This is called:
Prototype Design Pattern
Purpose of Prototype Pattern
The main purpose of Prototype Pattern is:
Create new objects by cloning existing objects instead of creating them from scratch.
Prototype improves:
- Performance
- Memory Usage
- Object Creation Speed
Real World Analogy
Imagine photocopying a document.
Instead of writing the entire document again:
Original Document
↓
Copy
You simply create copies.
Prototype works the same way.
When To Use Prototype?
Use Prototype when:
- Object creation is expensive
- Object initialization takes time
- Large object graphs exist
- Similar objects are frequently created
Examples:
- Employee Records
- Product Catalogs
- Insurance Policies
- Configuration Objects
- Game Characters
Traditional Object Creation
flowchart LR
A[Create Object]
A --> B[Load Data]
B --> C[Initialize Fields]
C --> D[Ready Object]
Every object repeats the same process.
Prototype Approach
flowchart LR
A[Prototype Object]
A --> B[Clone]
B --> C[New Object]
No need to repeat initialization.
Prototype Pattern Structure
classDiagram
class Prototype {
+clone()
}
class ConcretePrototype
Prototype <|-- ConcretePrototype
Prototype Pattern Flow
sequenceDiagram
participant Client
participant Prototype
Client->>Prototype: clone()
Prototype-->>Client: New Copy
Java Cloneable Interface
Java provides:
Cloneable
and
Object.clone()
to support cloning.
Simple Example
Employee Class
public class Employee implements Cloneable {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
@Override
protected Object clone()
throws CloneNotSupportedException {
return super.clone();
}
@Override
public String toString() {
return id + " " + name;
}
}
Client Code
public class PrototypeDemo {
public static void main(String[] args)
throws Exception {
Employee original =
new Employee(1, "Venu");
Employee clone =
(Employee) original.clone();
System.out.println(original);
System.out.println(clone);
}
}
Output
1 Venu
1 Venu
Memory Representation
flowchart TD
A[Original Object]
A --> B[Clone Object]
B --> C[Separate Memory]
Both objects are different instances.
Verify Different Objects
System.out.println(original == clone);
Output:
false
Both contain same data but are different objects.
Shallow Copy
Default cloning creates:
Shallow Copy
What Is Shallow Copy?
Primitive values are copied.
Object references are shared.
Example
public class Address {
String city;
public Address(String city) {
this.city = city;
}
}
public class Employee implements Cloneable {
int id;
Address address;
public Employee(int id, Address address) {
this.id = id;
this.address = address;
}
@Override
protected Object clone()
throws CloneNotSupportedException {
return super.clone();
}
}
Client Code
Address address =
new Address("San Antonio");
Employee emp1 =
new Employee(1, address);
Employee emp2 =
(Employee) emp1.clone();
emp2.address.city = "Dallas";
System.out.println(emp1.address.city);
Output
Dallas
Unexpected!
Why?
Because both employees share the same Address object.
Shallow Copy Diagram
flowchart TD
A[Employee 1]
B[Employee 2]
A --> C[Address]
B --> C[Address]
Both point to the same address.
Deep Copy
Deep Copy creates copies of nested objects as well.
Deep Copy Example
@Override
protected Object clone()
throws CloneNotSupportedException {
Employee employee =
(Employee) super.clone();
employee.address =
new Address(this.address.city);
return employee;
}
Deep Copy Flow
flowchart TD
A[Employee 1]
A --> B[Address 1]
C[Employee 2]
C --> D[Address 2]
Now both objects are independent.
Deep Copy Result
emp2.address.city = "Dallas";
Output:
Employee1 -> San Antonio
Employee2 -> Dallas
Perfect isolation.
Real World Example
Insurance Policy
Creating policy objects is expensive.
Policy contains:
Customer
Coverage
Premium
Beneficiaries
Documents
Instead of rebuilding:
Create Prototype
↓
Clone
↓
Modify Premium
Banking Example
Loan Application Templates
Home Loan Template
Personal Loan Template
Vehicle Loan Template
Clone template and modify values.
Banking Architecture
flowchart LR
A[Loan Prototype]
A --> B[Clone]
B --> C[Customer Loan]
Product Catalog Example
E-commerce system:
Laptop Template
Mobile Template
TV Template
Clone existing product configuration.
Update:
Price
Color
Memory
instead of recreating everything.
Game Development Example
Games frequently use Prototype.
Example:
Enemy Character
Clone:
Enemy 1
Enemy 2
Enemy 3
Enemy 4
Much faster than creating each character from scratch.
Prototype Registry Pattern
Enterprise applications often maintain prototypes in a registry.
Registry Diagram
flowchart TD
A[Prototype Registry]
A --> B[Employee Template]
A --> C[Loan Template]
A --> D[Policy Template]
Registry Example
Map<String, Employee> registry =
new HashMap<>();
registry.put(
"manager",
new Employee(1, "Manager"));
Later:
Employee copy =
(Employee) registry
.get("manager")
.clone();
Spring Framework Examples
Spring itself mostly uses Singleton scope.
However Prototype scope exists.
Prototype Bean Scope
@Component
@Scope("prototype")
public class Employee {
}
Behavior
Employee emp1 =
context.getBean(Employee.class);
Employee emp2 =
context.getBean(Employee.class);
Output:
Different Objects
Each request gets a new instance.
Singleton vs Prototype Scope
| Scope | Objects Created |
|---|---|
| Singleton | One |
| Prototype | Many |
| Request | Per Request |
| Session | Per Session |
Spring Scope Diagram
flowchart LR
A[Spring Container]
A --> B[Prototype Bean]
B --> C[New Object]
B --> D[New Object]
B --> E[New Object]
Framework Examples
Prototype concepts appear in:
| Framework | Usage |
|---|---|
| Spring | Prototype Scope |
| Hibernate | Entity Cloning |
| JPA | DTO Copying |
| Jackson | Object Duplication |
| Game Engines | Character Cloning |
Benefits
✅ Faster Object Creation
✅ Reduces Initialization Cost
✅ Improves Performance
✅ Simplifies Complex Object Creation
✅ Supports Dynamic Object Generation
✅ Reduces Repetitive Code
Limitations
❌ Deep Copy Can Be Complex
❌ Circular References Are Difficult
❌ Clone Logic Must Be Maintained
❌ Cloneable API Has Design Issues
Prototype vs Builder
| Feature | Prototype | Builder |
|---|---|---|
| Creates | Copy Existing Object | Build New Object |
| Performance | Faster | Slower |
| Complex Objects | Excellent | Excellent |
| Initialization Cost | Low | High |
Prototype vs Factory Method
| Feature | Prototype | Factory Method |
|---|---|---|
| Creation Method | Clone Existing Object | Create New Object |
| Speed | Faster | Normal |
| Use Case | Expensive Objects | Conditional Creation |
Interview Questions
What is Prototype Pattern?
A Creational Design Pattern that creates new objects by cloning existing objects.
Why use Prototype?
To avoid expensive object creation.
What is Shallow Copy?
Copies primitive values but shares object references.
What is Deep Copy?
Creates copies of nested objects as well.
What is Cloneable?
A Java marker interface that enables cloning.
What is Spring Prototype Scope?
Spring creates a new bean instance every time the bean is requested.
Key Takeaways
- Prototype creates objects by cloning.
- Useful when object creation is expensive.
- Java supports cloning using Cloneable.
- Shallow Copy shares references.
- Deep Copy creates independent object graphs.
- Spring supports Prototype Bean Scope.
- Frequently used in gaming, banking, insurance, and enterprise systems.