HardFunctions📖 Theory Question

Implementing the Factory Design Pattern in JavaScript Functions

💡

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.

Full Answer

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.

More Functions Questions

EasyWhat is the difference between call, apply, and bind?EasyHow do arrow functions differ from regular functions?EasyWhat is a pure function and why does it matter?EasyWhat are Higher-Order Functions (HOF)?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint