Introduction to Prototype Pattern
Prototype creates new objects by cloning existing ones, avoiding the cost of creating from scratch.
The Problem
Creating objects can be expensive:
- Complex initialization
- Database/network fetches
- Heavy computation
typescript1// Expensive to create from scratch each time2class AddressTemplate {3 constructor() {4 // Load default values from database5 // Validate against postal service6 // Fetch geocoding data7 }8}
The Solution: Prototype
Clone an existing object instead:
typescript1interface Cloneable<T> {2 clone(): T;3}45class AddressTemplate implements Cloneable<AddressTemplate> {6 constructor(7 public street: string,8 public city: string,9 public state: string,10 public postalCode: string,11 public country: string12 ) {}1314 clone(): AddressTemplate {15 return new AddressTemplate(16 this.street,17 this.city,18 this.state,19 this.postalCode,20 this.country21 );22 }23}2425// Clone and customize26const homeTemplate = new AddressTemplate('123 Main', 'NYC', 'NY', '10001', 'US');27const workAddress = homeTemplate.clone();28workAddress.street = '456 Office Blvd';
When to Use
- Expensive creation - Cloning is faster
- Runtime configuration - Object state determined at runtime
- Reduce subclassing - Clone and modify instead
- Object registries - Prototype manager for common templates
Shallow vs Deep Clone
typescript1// Shallow - nested objects shared2const shallow = { ...original };34// Deep - nested objects copied5const deep = JSON.parse(JSON.stringify(original));67// Custom deep clone for complex objects8clone(): ComplexObject {9 const cloned = new ComplexObject();10 cloned.primitive = this.primitive;11 cloned.nested = this.nested.clone(); // Clone nested objects12 return cloned;13}
Summary
Prototype is useful when object creation is expensive and you have a template to clone from. Pay attention to shallow vs deep cloning.