What is Prototype Pattern?
The Prototype Pattern is a creational design pattern that creates new objects by cloning an existing object instead of creating from scratch.
Why Use Prototype Pattern?
- Avoid expensive object creation
- Quickly duplicate existing objects
- Preserve object state (template-based creation)
- Improve performance
Real-Time Scenario
In an Invoice System:
- You have a predefined invoice template
- You want to create multiple similar invoices
👉 Instead of building from scratch, you clone it
Implementation
Step 1: Prototype Interface (Optional)
public interface IPrototype<T>
{
T Clone();
}
Step 2: Concrete Class
public class Invoice : IPrototype<Invoice>
{
public string Customer { get; set; }
public decimal Amount { get; set; }
public Invoice Clone()
{
return (Invoice)this.MemberwiseClone(); // shallow copy
}
}
Usage Example
// Original template
var template = new Invoice
{
Customer = "Template Customer",
Amount = 1000
};
// Clone it
var invoice1 = template.Clone();
invoice1.Customer = "Sai";
var invoice2 = template.Clone();
invoice2.Customer = "Kumar";
Console.WriteLine(invoice1.Customer); // Sai
Console.WriteLine(invoice2.Customer); // Kumar
Key Concept
Instead of:
var invoice = new Invoice();
// set all fields again ❌
We do:
var invoice = template.Clone();
👉 Faster and cleaner
Shallow vs Deep Copy
Shallow Copy
- Copies reference (default MemberwiseClone)
- Faster but shared references
Deep Copy
public Invoice Clone()
{
return new Invoice
{
Customer = this.Customer,
Amount = this.Amount
};
}
👉 Creates completely independent object
Advantages
- Fast object creation
- Reduces repetitive initialization
- Improves performance
- Useful for template-based systems
Disadvantages
- Deep copy can be complex
- Hidden bugs with shallow copy
- Requires careful implementation
When to Use
- When object creation is costly
- When many similar objects are needed
- When cloning is easier than building
- When working with templates
Real Project Mapping (.NET + Angular)
| Feature | Usage |
|---|---|
| Invoice templates | Prototype |
| Copy existing records | Prototype |
| UI form duplication | Prototype |
| Configuration cloning | Prototype |
Pro Tip (Advanced .NET Usage)
- Use AutoMapper or serialization for deep copy
- Combine with Builder Pattern for flexible cloning + modification
- Useful in test data generation
Summary
Prototype Pattern helps you:
- Clone existing objects efficiently
- Reduce object creation cost
- Work with templates easily
👉 Perfect for invoice templates, cloning data, reusable objects
Comments
Post a Comment