Prototype Pattern
The Prototype pattern creates new objects by copying an existing object (the prototype). Use it when object creation is expensive and a similar object already exists — cloning is faster and more convenient than instantiating from scratch.
Overview
The Prototype pattern produces new objects by cloning a pre-built instance — the prototype — instead of going through a constructor. It is useful when constructing the object is costly (network calls, heavy parsing) or when the configuration that produced the original is non-trivial and you want to reuse it.
When to use it
- Building an object from scratch is expensive but copying an existing one is cheap.
- You need many variations of the same base object and don't want to repeat its construction logic.
- Concrete class details should stay hidden — clients clone a known-good instance rather than wiring one up.
Example
interface Cloneable<T> { clone(): T }
class Shape implements Cloneable<Shape> {
constructor(public x: number, public y: number, public color: string) {}
clone(): Shape {
return new Shape(this.x, this.y, this.color);
}
}
const original = new Shape(10, 20, "red");
const copy = original.clone();
copy.x = 99;
console.log(original.x, copy.x); // 10 99Pros
- Skips expensive setup by copying an already-initialized instance.
- Hides concrete classes behind a `clone()` method — clients don't depend on constructors.
- Encourages composition: build a registry of prototypes and clone what you need.
Cons
- Deep-copying objects with circular references or shared resources is tricky.
- Every class in the graph must implement clone correctly — easy to forget a field.
- Loses the explicitness of a constructor signature.