From the course: Node.js: Design Patterns

Unlock the full course today

Join today to access over 24,900 courses taught by industry experts.

The Factory pattern

The Factory pattern

- In the real world, factories create products. An auto factory creates cars, a phone factory creates phones, and a chemical factory would create chemicals. Each of these factories create many variations of their product. The auto factory can create cars, trucks, SUVS, all different types of vehicles. If we want a truck, the factory will build it for us. In JavaScript, we also have different types of objects that we may need to instantiate. We can improve our code by encapsulating all of the constructors into a single module and creating a function that will will create the objects for us. This design pattern is called the factory method and the gang of four defined it as "define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. Let's take a look at how all of this works within JavaScript. Within our exercise…

Contents