15 minlesson

Introduction to Prototype Pattern

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
typescript
1// Expensive to create from scratch each time
2class AddressTemplate {
3 constructor() {
4 // Load default values from database
5 // Validate against postal service
6 // Fetch geocoding data
7 }
8}

The Solution: Prototype

Clone an existing object instead:

typescript
1interface Cloneable<T> {
2 clone(): T;
3}
4
5class 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: string
12 ) {}
13
14 clone(): AddressTemplate {
15 return new AddressTemplate(
16 this.street,
17 this.city,
18 this.state,
19 this.postalCode,
20 this.country
21 );
22 }
23}
24
25// Clone and customize
26const homeTemplate = new AddressTemplate('123 Main', 'NYC', 'NY', '10001', 'US');
27const workAddress = homeTemplate.clone();
28workAddress.street = '456 Office Blvd';

When to Use

  1. Expensive creation - Cloning is faster
  2. Runtime configuration - Object state determined at runtime
  3. Reduce subclassing - Clone and modify instead
  4. Object registries - Prototype manager for common templates

Shallow vs Deep Clone

typescript
1// Shallow - nested objects shared
2const shallow = { ...original };
3
4// Deep - nested objects copied
5const deep = JSON.parse(JSON.stringify(original));
6
7// Custom deep clone for complex objects
8clone(): ComplexObject {
9 const cloned = new ComplexObject();
10 cloned.primitive = this.primitive;
11 cloned.nested = this.nested.clone(); // Clone nested objects
12 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.