Factory
We begin our journey starting from what is probably the most simple and common design pattern in Node.js: factory.
A generic interface for creating objects
We already stressed the fact that, in JavaScript, the functional paradigm is often preferred to a purely object-oriented design, for its simplicity, usability, and small surface area. This is especially true when creating new object instances. In fact, invoking a factory, instead of directly creating a new object from a prototype using the new
operator or Object.create()
, is so much more convenient and flexible in several respects.
First and foremost, a factory allows us to separate the object creation from its implementation; essentially, a factory wraps the creation of a new instance giving us more flexibility and control in the way we do it. Inside the factory, we can create a new instance leveraging closures, using a prototype and the new
operator, using Object.create()
, or even returning a different instance based on a particular...