The prototype pattern is one of the Creational pattern groups. The responsibility is to create a new object through clone the existing object instead of using the new key. The new object is the same as the original object, and we can change its property does not impact the original object.
The singleton pattern should be used when a developer wants to:
For example, we will define a class that has the responsibility to generate a CSV file with a header and name.
export class ExportCsvFile { public _name: string; public _headers: string[] = ['#', 'Username', 'Email']; constructor(name: string, headers: string[]) { this._name = name; this._headers = [...this._headers, ...headers]; } public clone(): this { return Object.create(this); } }
const csvFile1 = new ExportCsvFile('CSV 1', []); console.log(csvFile1._name); console.log(csvFile1._headers); const csvFile2 = csvFile1.clone(); csvFile2._name = 'CSV 2' csvFile2._headers = [...csvFile2._headers, 'Is Activate', 'Last Login']; console.log(csvFile2._name); console.log(csvFile2._headers);
Execution result
CSV 1
[ '#', 'Username', 'Email' ]
CSV 2
[ '#', 'Username', 'Email', 'Is Activate', 'Last Login' ]
Pros:
Cons:
Thank you for reading, and happy coding!
I hope this article will help make the concepts of the Prototype Pattern