patterntypescriptModerate
Prototype Pattern: Clone Objects to Avoid Re-initialization Cost
Viewed 0 times
prototype patternclonedeep copyshallow copyobject cloningstructuredClonetemplate instance
Problem
Creating a new instance of an expensive-to-initialize object (database connection setup, large config tree) from scratch on every use is wasteful when you just need a slightly modified copy.
Solution
Implement a
clone() method on the class. Deep-copy the state so the clone is fully independent. TypeScript's structuredClone handles plain objects; classes need explicit clone logic.interface Cloneable<T> {
clone(): T;
}
class GameCharacter implements Cloneable<GameCharacter> {
constructor(
public name: string,
public stats: { hp: number; mp: number },
public inventory: string[]
) {}
clone(): GameCharacter {
return new GameCharacter(
this.name,
{ ...this.stats }, // shallow copy sufficient for primitives
[...this.inventory] // new array, same string refs (strings are immutable)
);
}
}
const template = new GameCharacter('Warrior', { hp: 100, mp: 50 }, ['sword']);
const player1 = template.clone();
player1.name = 'Alice';
player1.stats.hp = 120;
// template is unaffectedWhy
Cloning bypasses the constructor, preserving expensive state while letting you customize the copy. It is the basis for object pools and template-based instantiation patterns.
Gotchas
- Shallow copy is a bug when the object contains nested mutable objects — always decide consciously between deep and shallow.
Object.assignonly shallow-copies own enumerable properties. Prototype methods are not copied.structuredClonedeep-copies but cannot handle class instances with methods — the result is a plain object.- Circular references in the object graph will cause
structuredCloneto preserve cycles, butJSON.parse(JSON.stringify())will throw.
Revisions (0)
No revisions yet.