Skip to main content

Prototype Pattern

Clone existing objects efficiently instead of creating from scratch

Pattern Overview

🏗️ The Prototype Pattern - Efficient Object Cloning

Creates new objects by cloning existing instances rather than creating from scratch. Perfect for when object creation is expensive!

  • Core Problem Solved:
  • Avoid expensive object creation operations
  • Create similar objects with slight variations
  • Support runtime object creation without knowing concrete classes
  • Enable object creation without constructors
🔍 Three Implementation Approaches:
  • Shallow Clone: Copy object properties but not nested objects
  • Deep Clone: Recursively copy all nested objects and arrays
  • Registry Pattern: Store prototypes in registry for reuse
  • Real-World Applications:
  • Document templates and content management systems
  • Game entity spawning and character creation
  • Configuration management for different environments
  • Caching expensive-to-create objects
  • GUI component libraries with template widgets
  • Database record templates
  • Modern Usage Examples:
  • Object.create() and Object.assign() in JavaScript
  • Immutable.js and data structure libraries
  • React component cloning patterns
  • Redux state management with immutable updates

Examples:
Document template cloning
Input:
reportTemplate.clone().setTitle('Monthly Report').addSection(summarySection)
Output:
New document with custom title and additional section
Game entity creation
Input:
warriorPrototype.clone().moveTo(100, 200).upgradeArmor(10)
Output:
New warrior at position (100, 200) with upgraded armor
Environment configuration
Input:
baseConfig.clone().updateDatabaseHost('prod.db.com').setLogLevel('error')
Output:
Production config with updated database host and error-only logging

Concepts

Object CloningDeep/Shallow CopyTemplate ObjectsPerformance OptimizationRuntime Creation

Complexity Analysis

Time:O(n)
Space:O(n)

Implementation

shallow-clone

Time: O(1) | Space: O(1)
class Document {
  constructor(
    public title: string = '',
    public content: string = '',
    public metadata: Record<string, any> = {}
  ) {}

  // Shallow clone - only copies direct properties
  public clone(): Document {
    return new Document(
      this.title,
      this.content,
      this.metadata  // Reference copied, not deep cloned
    );
  }
}

// Alternative using Object.assign
const shallowClone = (obj: any) => Object.assign({}, obj);

// Or using spread operator
const shallowCloneSpread = (obj: any) => ({ ...obj });

// Usage
const template = new Document('Template', 'Base content', { author: 'John' });
const copy = template.clone();

// Issue: metadata is shared between original and copy
copy.metadata.author = 'Jane'; // This affects the original!