CreationalTypeScriptverifiedVerified

Prototype Pattern in TypeScript

Creates new objects by cloning an existing instance, avoiding the cost of building from scratch.

How to Implement the Prototype Pattern in TypeScript

1Step 1: Define the cloneable Prototype interface

interface Prototype<T> {
  clone(): T;
}

2Step 2: Implement cloneable Shape and GroupShape

class Shape implements Prototype<Shape> {
  constructor(
    public type: string,
    public x: number,
    public y: number,
    public color: string
  ) {}

  clone(): Shape {
    return new Shape(this.type, this.x, this.y, this.color);
  }

  toString(): string {
    return `${this.color} ${this.type} at (${this.x}, ${this.y})`;
  }
}

class GroupShape implements Prototype<GroupShape> {
  constructor(public name: string, public shapes: Shape[]) {}

  clone(): GroupShape {
    return new GroupShape(this.name, this.shapes.map(s => s.clone()));
  }
}

3Step 3: Create a prototype registry for template management

class ShapeRegistry {
  private templates = new Map<string, Shape>();

  register(key: string, shape: Shape): void {
    this.templates.set(key, shape);
  }

  create(key: string): Shape {
    const template = this.templates.get(key);
    if (!template) throw new Error(`No template: "${key}"`);
    return template.clone();
  }
}

4Step 4: Clone and customize objects from the registry

const registry = new ShapeRegistry();
registry.register("red-circle", new Shape("circle", 0, 0, "red"));

const c1 = registry.create("red-circle");
const c2 = registry.create("red-circle");
c2.x = 50;
c2.y = 100;

console.log(c1.toString()); // "red circle at (0, 0)"
console.log(c2.toString()); // "red circle at (50, 100)"
console.log(c1 === c2);     // false

Prototype Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Prototype Pattern in the Real World

Think of a cell dividing through mitosis. Instead of building a new cell from raw amino acids, the existing cell duplicates itself — copying its DNA, organelles, and membrane. The result is a fully functional copy produced far faster than assembling one molecule at a time.