prototype
Create new objects by copying (cloning) an existing object instead of constructing from scratch.
SKILL.mdskills/code-quality/prototype/SKILL.md
GitHubPrototype
Delegates object creation to the object itself via a clone() method. Useful when construction is expensive or complex and variations of an existing object are needed.
When to Use
- Object creation is expensive (DB reads, network calls, heavy computation) and cloning is cheaper
- You need many objects that are slight variations of a base object
- Classes to instantiate are specified at runtime
- Avoid subclassing just to configure an object
How to Apply
- Create a
Cloneable/Prototypeinterface with aclone()method - Implement
clone()in each concrete class (copy all fields; deep-copy mutable nested objects) - Optionally maintain a prototype registry (
Map<string, Prototype>) for named prototypes - Clients call
clone()instead ofnew
Example
interface Prototype<T> { clone(): T; }
class Shape implements Prototype<Shape> {
constructor(
public color: string,
public x: number,
public y: number,
) {}
clone(): Shape { return new Shape(this.color, this.x, this.y); }
}
// Cheap variant creation
const base = new Shape('red', 0, 0);
const copy = base.clone();
copy.x = 10; // base is unaffected