A function factory for objects is a function that returns new objects. A function factory for objects is a higher-order function that returns a new function which, when called, generates and returns an object with specific properties.
This pattern allows you to create multiple objects with similar structures but different values, enhancing code reusability and reducing redundancy.
This pattern is useful for creating multiple objects with similar structures but different data. Function factories help reduce code duplication and enhance code reusability, especially when creating complex objects dynamically.
Here's an example of a function factory that creates user objects:
// Function factory to create user objects
function createUserFactory(defaultRole) {
return function(name, age) {
return {
name: name,
age: age,
role: defaultRole,
// Method to display user details
getDetails() {
return `${this.name}, ${this.age} years old, ${this.role}`;
}
};
};
}
// Creating different user factories
const createAdmin = createUserFactory('Admin');
const createGuest = createUserFactory('Guest');
// Using the factories to create user objects
const user1 = createAdmin('John', 30);
const user2 = createGuest('Jane', 25);
console.log(user1.getDetails()); // Output: John, 30 years old, Admin
console.log(user2.getDetails()); // Output: Jane, 25 years old, Guest
Here is another example of a function factory that creates person objects:
// Function factory to create person objects
function createPerson(firstName, lastName, age, isMarried) {
return {
firstName,
lastName,
age,
isMarried,
fullName() {
return `${this.firstName} ${this.lastName}`;
},
celebrateBirthday() {
this.age += 1;
console.log(`Happy Birthday ${this.firstName}! You are now ${this.age} years old.`);
}
};
}
// Using the function factory to create new person objects
const person1 = createPerson('John', 'Doe', 30, false);
const person2 = createPerson('Jane', 'Smith', 25, true);
console.log(person1.fullName()); // Output: John Doe
console.log(person2.fullName()); // Output: Jane Smith
person1.celebrateBirthday(); // Output: Happy Birthday John! You are now 31 years old.
person2.celebrateBirthday(); // Output: Happy Birthday Jane! You are now 26 years old.
Function factories for objects provide a powerful way to create multiple objects with similar structures but different data. This pattern is especially useful in React for dynamic state initialization, creating configuration objects, and generating utility objects. Utilizing function factories can lead to more modular, maintainable, and reusable code.