Creational · DWG NO. 009

Prototype

Create new objects by copying an existing, fully-configured instance instead of rebuilding one from scratch.

TypeCreational
ScopeSingle object
ComplexityLow
Common inObject pools, game entities, document templates

Rebuilding an object is more expensive than copying one

Some objects are costly or fiddly to construct — one loaded from a database, or configured through many steps. If you need ten slightly different variants, re-running that setup ten times is wasteful when nine of them are 95% identical to an existing instance.

Clone, then tweak

The object implements a `clone()` method that returns a new, independent copy of itself (a deep copy for any nested state). Callers clone an existing prototype and then adjust just the fields that differ.

Prototype(configured)clone()Copy ACopy B

Cloning a configured enemy template

`spawn()` deep-clones the template and only overrides position — every other stat is copied, not recomputed.

enemy-prototype.js
class Enemy {
  constructor(stats) { this.stats = stats; }

  clone() {
    return new Enemy(structuredClone(this.stats));
  }
}

const goblinTemplate = new Enemy({
  hp: 30, speed: 2, loot: ["copper coin", "dagger"], x: 0, y: 0,
});

function spawn(template, x, y) {
  const enemy = template.clone();
  enemy.stats.x = x;
  enemy.stats.y = y;
  return enemy;
}

const a = spawn(goblinTemplate, 10, 5);
const b = spawn(goblinTemplate, 40, 12);

console.log(a.stats.x, b.stats.x);           // 10 40
console.log(a.stats.loot === b.stats.loot);  // false — independent copies

Trade-offs