← Back to Home

Prototype Pattern

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

What is it?

The Prototype pattern lets you copy existing objects without making your code dependent on their concrete classes.

Example

interface Shape {
  clone: () => Shape;
  draw: () => string;
}

class Circle implements Shape {
  radius: number;
  constructor(radius: number) {
    this.radius = radius;
  }

  clone(): Shape {
    return new Circle(this.radius);
  }

  draw() {
    return `Circle with radius ${this.radius}`;
  }
}

class Rectangle implements Shape {
  width: number;
  height: number;
  constructor(width: number, height: number) {
    this.width = width;
    this.height = height;
  }

  clone(): Shape {
    return new Rectangle(this.width, this.height);
  }

  draw() {
    return `Rectangle ${this.width}x${this.height}`;
  }
}

Common Uses

  • Cloning objects when construction is expensive
  • Preserving existing state in copies
  • Prototype registries for creating new objects

When to Use

  • When creating a new object is costly or complex
  • When objects are similar but not identical

Caution

  • Deep vs. shallow copy can be tricky
  • May hide dependencies if used excessively