Factory Pattern: Decoupling Object Creation
Learn how to use factory pattern to decouple the object creation.
We'll cover the following
We’ll begin our journey with one of the most common design patterns in Node.js: Factory. As you’ll see, the Factory pattern is very versatile and has more than just one purpose. Its main advantage is its ability to decouple the creation of an object from one particular implementation. This allows us, for example, to create an object whose class is determined at runtime. Factory also allows us to expose “a surface area” that’s much smaller than that of a class; a class can be extended or manipulated, while a factory, being just a function, offers fewer options to the user, making it more robust and easier to understand. Finally, a factory can also be used to enforce encapsulation by leveraging closures.
Decoupling object creation and implementation
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 class 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 creation of an object 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 choose to create a new instance of a class using the new
operator, leverage closures to dynamically build a stateful object literal, or even return a different object type based on a particular condition. The consumer of the factory is totally agnostic about how the creation of the instance is carried out. The truth is that, by using the new
operator, we’re binding our code to one specific way of creating an object, while with a factory, we can have much more flexibility, almost for free. As a quick example, let’s consider a simple factory that creates an Image
object.
Get hands-on with 1400+ tech skills courses.