The Prototype Pattern is a creational design pattern that enables you to create object copies (clones) without depending on their concrete classes.
Purpose
- Avoid the cost of creating a new object from scratch.
- Simplify object creation when it’s complex or time-consuming.
- Duplicate objects dynamically at runtime.
Components
- Prototype Interface
Declares aclone()
method. - Concrete Prototype
Implements theclone()
method to return a copy of itself. - Client
Uses the prototype to clone new objects instead of creating them manually.
Steps to Implement in Java
1. Define the Prototype Interface
public interface Prototype {
Prototype clone();
}
2. Create a Concrete Class That Implements Prototype
public class Book implements Prototype {
private String title;
private String author;
private int pages;
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.pages = pages;
}
// Copy constructor
public Book(Book book) {
this.title = book.title;
this.author = book.author;
this.pages = book.pages;
}
@Override
public Prototype clone() {
return new Book(this);
}
@Override
public String toString() {
return "Book [title=" + title + ", author=" + author + ", pages=" + pages + "]";
}
}
3. Use in a Client Class
public class Main {
public static void main(String[] args) {
Book original = new Book("Java Design Patterns", "Author A", 300);
Book copy = (Book) original.clone();
System.out.println("Original: " + original);
System.out.println("Copy: " + copy);
}
}
Output
Original: Book [title=Java Design Patterns, author=Author A, pages=300]
Copy: Book [title=Java Design Patterns, author=Author A, pages=300]
Key Points
- Shallow Copy: Copies field values (suitable for primitives and immutable types).
- Deep Copy: Required if your object contains references to other mutable objects.
- Prefer using your own cloning mechanism over Java’s built-in
Cloneable
interface for better control.
Use Cases
- Game object duplication (e.g., enemies, items).
- Document or form templates.
- Caching complex objects.
Summary
The Prototype Pattern is useful when creating a new object is expensive or complicated. By cloning a pre-existing instance, you improve performance and simplify object creation.