Factory Pattern
Use a factory function in order to create objects
With the Factory Pattern, we can use a special function — the factory function — to create many of the same objects.
Implementation:
A factory function can be any function that returns an object.
const createEmployee = (firstName, lastName) => ({
id: crypto.randomUUID(),
createdAt: Date.now(),
firstName,
lastName,
fullName: `${firstName} ${lastName}`,
});
createEmployee("John", "Doe");
createEmployee("Sarah", "Doe");
createEmployee("Lydia", "Hallie");
TradeOffs:
DRY : It can easily return a custom object depending on the current environment, or user-specific configuration without having to repeat the same code over and over.
Not really a pattern: In JavaScript, the factory pattern isn’t much more than a function that returns an object without using the new keyword. ES6 arrow functions allow us to create small factory functions that implicitly return an object each time.
However, in many cases it may be more memory efficient to create new instances instead of new objects each time.