Hint
Think about how you can use a single function to create objects of different classes, and how this can help in managing complexity and improving code reusability.
The Factory design pattern is a creational pattern that provides an interface for creating objects without specifying the exact class of object that will be created. In JavaScript, we can implement the Factory pattern using functions. Here's an example:
function createUser(type, name) {
if (type === 'admin') {
return new AdminUser(name);
} else if (type === 'moderator') {
return new ModeratorUser(name);
} else {
return new RegularUser(name);
}
}
class AdminUser {
constructor(name) {
this.name = name;
this.role = 'admin';
}
}
class ModeratorUser {
constructor(name) {
this.name = name;
this.role = 'moderator';
}
}
class RegularUser {
constructor(name) {
this.name = name;
this.role = 'regular';
}
} In this example, the createUser function acts as a factory, creating and returning objects of different classes based on the input type.