The Factory design pattern is a widely used software design pattern in JavaScript. It is a creational pattern that is used to create objects based on a common interface or blueprint. The Factory pattern encapsulates the object creation logic and allows us to create different objects without exposing the object creation logic to the client.
Here is an example of implementing the Factory pattern in JavaScript:
In the above example, the createPerson
function acts as a factory function that encapsulates the logic for creating a person
object. It takes in the required properties for the person object and returns an object with those properties along with a method sayHello
.
Using this approach, we can create any number of person objects without having to duplicate the creation logic or expose it to the client.