Prototype
Create new objects by copying an existing instance.
Use it when
Creating an object from scratch is expensive, or you need copies independent of their concrete classes.
/**
* Prototype: create new invoices by copying a ready-made template.
*
* Real-world scenario: a billing app. The company details, payment terms and the
* standard setup fee are filled in once, on a template invoice. Each customer's
* invoice is a clone of that template plus their own items, so nothing is set up
* twice and the template itself never changes.
*/
class Invoice {
customer = "(not set)";
readonly company: string;
readonly paymentTerms: string;
readonly items: string[];
constructor(company: string, paymentTerms: string, items: string[] = []) {
this.company = company;
this.paymentTerms = paymentTerms;
this.items = items;
}
clone(): Invoice {
// A real Invoice with its own copy of the items array, not a shared one.
// (structuredClone() also copies deeply, but returns a plain object
// without Invoice's methods.)
const copy = new Invoice(this.company, this.paymentTerms, [...this.items]);
copy.customer = this.customer;
return copy;
}
summary(): string {
return `${this.customer}: ${this.items.join(", ")} (${this.paymentTerms})`;
}
}
function clientCode(): void {
// The prototype: set up once.
const template = new Invoice("Acme Ltd", "pay in 30 days", ["Setup fee $100"]);
// New invoices are copies of the template, then customised.
const asha = template.clone();
asha.customer = "Asha";
asha.items.push("Website design $900");
const ravi = template.clone();
ravi.customer = "Ravi";
ravi.items.push("Logo design $300");
console.log(asha.summary());
console.log(ravi.summary());
console.log("Template unchanged:", template.items);
// Why clone() copies the array: a shallow copy shares the same items array,
// so adding to the copy quietly changes the template too.
const shallow = { ...template };
shallow.items.push("Oops");
console.log("After a shallow copy:", template.items);
}
clientCode();
// Output:
// Asha: Setup fee $100, Website design $900 (pay in 30 days)
// Ravi: Setup fee $100, Logo design $300 (pay in 30 days)
// Template unchanged: [ 'Setup fee $100' ]
// After a shallow copy: [ 'Setup fee $100', 'Oops' ]How it works
| Role | Classes | What it does |
|---|---|---|
| Prototype | Invoice | A ready-made template whose clone() returns a new Invoice with its own items array |
| Client | clientCode() | Clones the template and customises each copy |